1

我刚开始联网,这是我编译它们时的第一个程序服务器客户端 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;

}

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

4

2 回答 2

2

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

于 2013-09-07T15:53:13.177 回答
1

struct sock_addr_in server_addr;

它是sockaddr_in

于 2013-09-07T16:43:08.633 回答