我是套接字编程的新手,我试图运行执行以下代码,但没有任何运气! 操作系统:Ubuntu 16.10 编译:GCC
echo服务正在端口7上运行。
这是代码:将IP地址作为第一个参数,将端口号作为第2个,将字符串作为第3个发送。
void exit_with_error(char *);
void exit_with_error(char *err_msg)
{
printf("%s",err_msg);
exit(EXIT_FAILURE);
}
int main(int argc, char* argv[] )
{
system("clear");
int socket_num,port_num, recv_bytes;
char *ip_addr;
char *Txstring;
char *RxString;
struct sockaddr_in servAddr;
ip_addr=argv[1];
port_num=atoi(argv[2]);
Txstring=argv[3];
//Construct server address structure
memset(&servAddr,0,sizeof(servAddr));
servAddr.sin_family=AF_INET;
servAddr.sin_addr.s_addr=inet_network(ip_addr);
servAddr.sin_port = htons(port_num) ;
socket_num=socket(AF_INET, SOCK_STREAM,0);
if(socket_num==-1)
exit_with_error("Socket creation failed...\n");
//connect to echo server
if(connect(socket_num , (struct sockaddr *) &servAddr, sizeof(servAddr) ) < 0)
exit_with_error("Connection failed !\n");
//Send the string to server
send(socket_num, Txstring, strlen(Txstring), 0);
//Receive the string
recv(socket_num, RxString, strlen(Txstring), 0);
printf("Received; %s", RxString);
close(socket_num);
return 0;
}
当我将程序运行为:./prog 127.0.0.1 7 Hello
输出为:Connection failed !
我无法弄明白为什么!