我正在尝试在给定命令行参数的情况下初始化套接字,argv1是ip,argv2是port。该端口可以根据需要工作,但是创建IP地址是个问题。预期输入为./client.out 10.5.10.20 88888 这是客户端,服务器端成功创建了端口号。
// Socket information
char ipadd[255];
strcpy(ipadd,argv[1]);
int portval = atoi(argv[2]);
struct sockaddr_in server_info, client_info;
int s_addrlen = sizeof(server_info);
int c_addrlen = sizeof(client_info);
memset(&server_info, 0, s_addrlen);
memset(&client_info, 0, c_addrlen);
server_info.sin_family = PF_INET;
server_info.sin_addr.s_addr = inet_aton(argv[1], &server_info);
server_info.sin_port = htons(portval);
在编译时会收到警告
expected ‘struct in_addr *’ but argument is of type ‘struct sockaddr_in *’
extern int inet_aton (const char *__cp, struct in_addr *__inp) __THROW;
答案 0 :(得分:0)
这是对我有用的解决方案
char ipadd[255];
strcpy(ipadd,argv[1]);
int portval = atoi(argv[2]);
struct sockaddr_in server_info, client_info;
int s_addrlen = sizeof(server_info);
int c_addrlen = sizeof(client_info);
memset(&server_info, 0, s_addrlen);
memset(&client_info, 0, c_addrlen);
server_info.sin_family = PF_INET;
server_info.sin_addr.s_addr = htonl(INADDR_ANY);
inet_aton(argv[1], &server_info.sin_addr);
server_info.sin_port = htons(portval);