On the programming of Linux C Network

Source: Internet
Author: User
Tags server port htons

The following picture is taken from the UNIX Network programming Volume One, the framework of this simple C/s program

Service-side Programs

#include <stdlib.h>#include <sys/types.h>#include <stdio.h>#include <sys/socket.h>#include <linux/in.h>#include <string.h>intMain () {intSFP,NFP;/ * Define two descriptors * /    structSockaddr_in S_add,c_add;intSin_size;unsigned  Shortportnum=0x8888;/ * Use port on server * /    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 the following address and port are used for monitoring */Bzero (&s_add,sizeof(structsockaddr_in));    S_add.sin_family=af_inet; S_add.sin_addr.s_addr=htonl (Inaddr_any);/ * This 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 to 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);/ * Accept the server to use the function, the call will go into the blocking state, waiting for the user to connect, when there is no client connection, the program stopped here, do not see the subsequent printing, when a client to connect, the program executes once, and then loop back here to continue waiting.            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));/ * Use write to send a message to the client, or you can try using another function 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;}

Client program

#include <stdlib.h>#include <sys/types.h>#include <stdio.h>#include <sys/socket.h>#include <linux/in.h>#include <string.h>intMain () {intCfD/ * File descriptor * /    intRecbytes;intSin_size;Charbuffer[1024x768]= {0};/ * Accept buffer * /    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");/ * Build sockets using the Internet, TCP streaming * /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 port information, the concrete structure 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.123");/ * IP is converted to 4-byte shaping and needs to be changed according to the server IP when using * /S_add.sin_port=htons (Portnum);/* Here htons is to convert 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);/* This prints out the small end and what we usually see is the opposite. */    / * 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, receive characters 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 ();/ * This sentence is for the program to pause here, you can use Netstat to view the current connection * /Close (CFD);/ * Close the connection, this communication is complete * /    return 0;}

Note that the client sends the address to fill in the IP address of your own server, such as my client and service are on the same machine, with the command IP addr Show view IP
My IP is 196.124.1.123, fill in, or can fill 127.0.0.1 this is a return IP, that is, the IP of your machine, fill in other IP links not to the server

Run

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

On the programming of Linux C Network

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.