gpt4 book ai didi

c++ - 使用 g++ 的 TCP 服务器客户端

转载 作者:可可西里 更新时间:2023-11-01 02:39:44 25 4
gpt4 key购买 nike

我刚开始联网,这是我的第一个程序服务器客户端 TCP 连接当我编译它们时出现关于结构的错误

client.cpp: In function ‘int main()’:
client.cpp:15:2: error: ‘sock_addr_in’ was not declared in this scope
client.cpp:15:15: error: expected ‘;’ before ‘server_addr’
client.cpp:18:1: error: ‘server_addr’ was not declared in this scope

服务器.cpp

#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdlib.h>
#include <unistd.h>

using namespace std;

int main()
{
struct in_addr addr;
char msg[100];
int conn_sock,comm_sock,n;
struct sockaddr_in server_addr,client_addr;
conn_sock=socket(AF_INET,SOCK_STREAM,0)
server_addr.sin_family=AF_INET;
server_addr.sin_port=htons(1234);
server_addr.sin_addr.s_addr=inet_addr("127.0.0.1");

bind(conn_sock, (struct sockaddr *)&server_addr,sizeof(server_addr));

listen(conn_sock,10);
comm_sock=accept(conn_sock, (struct sockaddr *)&client_addr, (socklen_t *)&client_addr);

cout<<"n\n\nConnection established with client";
n=read(comm_sock,msg,100);

cout<<"\n\nReceived data from client is :\n"<<msg;

close(comm_sock);
close(conn_sock);
return 0;
}

客户端.cpp

#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>
#include <unistd.h>

using namespace std;

int main(){

char msg[100]="hello";
int conn_sock;
struct sock_addr_in server_addr;
conn_sock=socket(AF_INET,SOCK_STREAM,0);

server_addr.sin_family=AF_INET;
server_addr.sin_port=htons(1234);
server_addr.sin_addr.s_addr=inet_addr("127.0.0.1");

connect(conn_sock, (struct sockaddr *)&server_addr, sizeof (server_addr));

write(conn_sock,msg,strlen(msg));
close(conn_sock);
return 0;

}

我在这个程序中遇到错误,我不知道这里出了什么问题 =(请问有人可以在这里指导我吗?

最佳答案

它甚至可以编译吗?我看到连接步骤中缺少一个分号:“conn_sock=socket(AF_INET,SOCK_STREAM,0)”

关于c++ - 使用 g++ 的 TCP 服务器客户端,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18675040/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com