Simple example of C language socket network programming under Linux

Source: Internet
Author: User
Tags server port htons

Original articles, reproduced please indicate reproduced the words and sources, thank you!

This gives an example of a simple socket network programming under Linux, communicates with the TCP protocol, listens on the server, sends the data to the client after receiving the client's connection, and the client prints and closes after receiving the data. There are detailed instructions in the program, in which the specific structure and functions of the implementation can refer to other information.

Program Description: Here the server port number and IP address using fixed settings, the migration can be changed according to the specific circumstances, can be rewritten as a parameter to pass better, here for convenience, use fixed.

The server can be run without changes at the time of migration, the client will change IP to the address of the servers, and then compile and run. You can use Netstat to view the appropriate run status.

/************************************* file name: SERVER.C Linux Socket Network Programming Simple example-server port is set to 0x8888 (port and address can be changed according to the actual situation, or use Parameter passed in) the server address is set to 192.168.1.104 Author: kikilizhm#163.com (change # to @)*/#include<stdlib.h>#include<sys/types.h>#include<stdio.h>#include<sys/socket.h>#include<linux/inch.h>#include<string.h>intMain () {intSFP,NFP;/*define two descriptors*/  structsockaddr_in S_add,c_add; intsin_size; unsigned Shortportnum=0x8888;/*Server Port Usage*/printf ("hello,welcome to my server!\r\n"); SFP= Socket (Af_inet, Sock_stream,0); if(-1==SFP) {printf ("socket fail! \ r \ n"); return-1; } printf ("Socket OK!\r\n"); /*populate the server port address information so that this address and port are used to listen*/bzero (&s_add,sizeof(structsockaddr_in)); S_add.sin_family=af_inet; S_add.sin_addr.s_addr=htonl (Inaddr_any);/*here the address uses full 0, i.e. all*/S_add.sin_port=htons (Portnum); /*bind port with bind*/  if(-1= = Bind (SFP, (structSOCKADDR *) (&s_add),sizeof(structSOCKADDR)))  {printf ("bind fail!\r\n"); return-1; } printf ("bind OK!\r\n"); /*start listening on the appropriate port*/  if(-1= = Listen (SFP,5) {printf ("Listen fail!\r\n"); return-1; } printf ("Listen ok\r\n");  while(1) {sin_size=sizeof(structsockaddr_in); /*The accept service side uses the function, when the call enters the blocking state, waits for the user to make the connection, when does not have the client to connect, the program stops here, does not see the subsequent printing, when has the client to connect, the program executes once, then loops again here to continue waits.     The second parameter of the accept here is used to obtain the port and address information for the client. */NFP= Accept (SFP, (structSOCKADDR *) (&c_add), &sin_size); if(-1==NFP) {printf ("Accept fail!\r\n"); return-1; } printf ("Accept Ok!\r\nserver start get connect from% #x:% #x \ r \ n", Ntohl (C_ADD.SIN_ADDR.S_ADDR), Ntohs (C_add.sin_port)); /*here, you can use write to send information to the client, or you may try to use other functions to implement*/  if(-1= = Write (NFP,"hello,welcome to my server \ r \ n", +) {printf ("Write fail!\r\n"); return-1; } printf ("Write ok!\r\n");    Close (NFP);  } close (SFP); return 0; }  

---

/************************************* file name: CLIENT.C Linux Socket Network Programming Simple example-the client program server port is set to 0x8888 (port and address can be changed according to the actual situation, or make With parameter incoming) the server address is set to 192.168.1.104 Author: kikilizhm#163.com (change # to @)*/#include<stdlib.h>#include<sys/types.h>#include<stdio.h>#include<sys/socket.h>#include<linux/inch.h>#include<string.h>intMain () {intCfD/*File Descriptor*/  intrecbytes; intsin_size; Charbuffer[1024x768]={0};/*Accept Buffers*/  structSockaddr_in S_add,c_add;/*Storage server and local IP, port and other information structures*/unsigned Shortportnum=0x8888;/*the communication port used by the server can be changed to be the same as the server*/printf ("hello,welcome to client!\r\n"); /*establishing sockets using the Internet, TCP stream transmission*/CFD= Socket (Af_inet, Sock_stream,0); if(-1==CfD) {printf ("socket fail! \ r \ n"); return-1; } printf ("Socket OK!\r\n"); /*constructs the server side IP and the port information, the concrete structure body may check the data*/bzero (&s_add,sizeof(structsockaddr_in)); S_add.sin_family=af_inet; S_add.sin_addr.s_addr= Inet_addr ("192.168.1.104");/*IP conversion to 4-byte shaping that needs to be changed according to the server IP*/S_add.sin_port=htons (Portnum);/*here htons is the short data byte sequence from the host to the network type, in fact, the 2 bytes of data before and after two bytes switching, and the corresponding Ntohs effect, the same substance, but the name is different. Htonl and Ntohl are operations of 4-byte shaping.  Change the 0x12345678 to 0x78563412, the name is different, the content 22 is the same, generally the network is big-endian, the CPU of PPC is large, the CPU of x86 is small, the arm can configure the size end, need to ensure that the byte sequence is correct when receiving. */printf ("s_addr =% #x, port:% #x \ r \ n", S_add.sin_addr.s_addr,s_add.sin_port);/*The small end printed here is the opposite of what we usually see. */    /*Client Connection server, parameters are socket file descriptor, address information, address structure size*/  if(-1= = Connect (CFD, (structSOCKADDR *) (&s_add),sizeof(structSOCKADDR)))  {printf ("Connect fail!\r\n"); return-1; } printf ("Connect OK!\r\n"); /*Connection succeeded, character received from server*/  if(-1= = (Recbytes = Read (Cfd,buffer,1024x768)) {printf ("read data fail!\r\n"); return-1; } printf ("Read ok\r\nrec:\r\n"); Buffer[recbytes]=' /'; printf ("%s\r\n", buffer); GetChar (); /*to pause the program here, you can use Netstat to view the current connection*/Close (CFD);/*Close the connection, this communication is complete*/  return 0; }  

Run:

Simple example of C language socket network programming under Linux

Related Article

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.