Linux Network Programming TCP

Source: Internet
Author: User

The notes were not saved before the study, and a case was rewritten this time.

Client Implementation Program code:

#include <string.h>#include<stdlib.h>#include<stdio.h>#include<fcntl.h>#include<unistd.h>#include<netinet/inch.h>#include<arpa/inet.h>#defineDef_tcp_srv_port 19868intMain () {structsockaddr_in addr; structsockaddr_in srv_addr; intNet_sock; intnew_fd; intRes; intLen; Charbuff[ -]; //1. Socket initialization//1.1 Creating SocketsNet_sock = socket (Af_inet,sock_stream,0); if( -1==Net_sock) {printf ("Create socket error!\r\n"); return-1; }    //1.2 Initialize addressBzero (&AMP;ADDR,sizeof(structsockaddr_in)); Addr.sin_addr.s_addr=htonl (Inaddr_any); Addr.sin_family=af_inet; Addr.sin_port=htons (Def_tcp_srv_port); //1.3 bind AddressBind (Net_sock, (structSOCKADDR *) &addr,sizeof(structsockaddr)); //MonitorListen (Net_sock,5 ); Len=sizeof(structsockaddr); NEW_FD= Accept (Net_sock, (structSOCKADDR *) (&AMP;SRV_ADDR),&Len); printf ("Server ip:%s\r\n", Inet_ntoa (SRV_ADDR.SIN_ADDR)); Res= recv (new_fd, Buff, the,0); Buff[res]=' /'; printf ("Get:%s\r\n", Buff);    Close (Net_sock); return 0;};

Service-Side program code:

#include <string.h>#include<stdlib.h>#include<stdio.h>#include<fcntl.h>#include<unistd.h>#include<netinet/inch.h>#include<arpa/inet.h>#defineDef_tcp_srv_port 19868intMain () {structsockaddr_in srv_addr; intsock; intRes; Charbuff[ -]; //Creating SocketsSock = socket (Af_inet,sock_stream,0); if( -1==sock) {printf ("Create sock failed\r\n"); return-1; }    //set the address to bindBzero (&AMP;SRV_ADDR,sizeof(structsockaddr_in)); Srv_addr.sin_addr.s_addr= Inet_addr ("192.168.1.21"); Srv_addr.sin_family=af_inet; Srv_addr.sin_port=htons (Def_tcp_srv_port); //Connectionres = connect (sock, (structSOCKADDR *) (&AMP;SRV_ADDR),sizeof(structsockaddr)); if( -1==Res) {printf ("Connect failed\r\n"); return-1; } printf ("Please input data:\r\n"); Fgets (Buff, -, stdin); //Send DataSend (sock, buff, strlen (buff),0); Close (sock);}

Linux Network Programming TCP

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.