Linux_C socket clinet.c

來源:互聯網
上載者:User

標籤:style   blog   io   color   ar   os   sp   for   div   

 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

Linux_C socket clinet.c

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.