Linux_C socket clinet.c
1 /* timeclnt.c - a client for timeserv.c 2 * usage: timeclnt hostname portnumber 3 */ 4 #include <stdio.h> 5 #include <sys/types.h> 6 #include <sys/socket.h> 7 #include <netinet/in.h> 8 #include <netdb.h> 9 10 #define oops(msg) {perror(msg); exit(1); } 11 #define oopsn(msg, x) {perror(msg); exit(x);}; 12 int main(int argc, char* argv[]) { 13 struct sockaddr_in servadd; 14 struct hostent *hp; 15 int sock_id, sock_fd; 16 char message[BUFSIZ]; 17 int messlen; 18 int connect_num; 19 /*** Step 1: Get a socket ***/ 20 sock_id=socket(PF_INET, SOCK_STREAM, 0); 21 if(sock_id==-1) 22 oops("socket"); 23 /*** Step 2: connect to server need to build address (host, port)of server first ***/ 24 bzero((void*)&servadd, sizeof(servadd)); 25 hp=gethostbyname(argv[1]); 26 if(hp==NULL) 27 oops(argv[1]); 28 29 bcopy(hp->h_addr, (struct sockaddr*)&servadd.sin_addr, hp->h_length); 30 servadd.sin_port=htons(atoi(argv[2]));/**这里记住一定要atoi转换,不然connect不起**/ 31 servadd.sin_family=AF_INET; 32 33 if((connect_num=connect(sock_id, (struct sockaddr*)&servadd, sizeof(servadd)))!=0) 34 { 35 printf("connect fail is %d.",connect_num); 36 oopsn("connnnnect!!!!!", connect_num); 37 } 38 39 /*** Step 3: transfer data from server , then hangup ***/ 40 messlen=read(sock_id, message, BUFSIZ); 41 if(messlen == 1) 42 oops("read"); 43 if(write(1, message, messlen)!= messlen) 44 oops("write"); 45 close(sock_id); 46 return 0; 47 }
gcc timeclnt.c -o timeclnt
./timeclnt 主机名 portnum
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。