Use C to write the socket program under Linux

Source: Internet
Author: User
Tags function definition socket error htons

Ten years did not write C, this can be said to re-learn, the bottom of the program is to change from W.richard Stevens's masterpiece-Networking apis:sockets and XTI, for two reasons: (1) In my development environment scientific LI Nux 7.0 on the normal compile, probably because the Stevens program is written on UNIX, and Linux slightly different; (2) Stevens uses #define to redefine a number of commonly used functions, which, in the first instance, would be confused, and I would have used these functions as primitive functions.

This program has a client and a server,server to start, wait for the client to connect, after the client link back to the system time, the client will receive the value printed. The first program is server and the second program is client. Here we will explain each function in detail because ... I am a beginner!!

1#include <sys/socket.h>2#include <sys/types.h>3#include <stdio.h>4#include <unistd.h>5#include <netinet/inch.h>6#include <string.h>7#include <arpa/inet.h>8#include <time.h>9 Ten Const intMAXLINE = -; One Const intListenq =1024x768; A  - intMainintargcChar**argv) { -     intlistenfd, CONNFD; the     structsockaddr_in servaddr; -     CharBuff[maxline]; -  - time_t ticks; +LISTENFD = socket (af_inet, Sock_stream,0); -  +Bzero (&AMP;SERVADDR,sizeof(SERVADDR)); Aservaddr.sin_family =af_inet; atSERVADDR.SIN_ADDR.S_ADDR =htonl (inaddr_any); -Servaddr.sin_port = htons (1513); -  -Bind (LISTENFD, (structSOCKADDR *) &servaddr,sizeof(SERVADDR)); - Listen (LISTENFD, Listenq); -  in      for( ; ; ) { -CONNFD = Accept (LISTENFD, (structSOCKADDR *) NULL, and NULL); to  +Ticks =Time (NULL); -snprintf (Buff,sizeof(Buff),"%.24s\r\n", CTime (&ticks)); the write (CONNFD, buff, strlen (buff)); *  $ Close (CONNFD);Panax Notoginseng     } -  the}
  • Line 19th: Set up a socket connection, regardless of the client or server program, will call this function at the beginning, the three parameters required by the function are as follows:
    • First: Af_inet says to set up a socket connection for the Internet, which is basically fixed filling in this value, the socket function and af_inet are the definitions in the Socket.h, and that's why the first line is going to introduce this title, most of The socket is related to the function, and the constant is the definition of this target file.
    • Second: There are two values that can be transferred-Sock_stream and Sock_dgram, to set up a TCP connection into the sock_stream, to establish a UDP connection to the Sock_dgram.
    • The third argument: usually the 0,socket will choose the most appropriate message agreement, that is, the second argument, where is it used when it is not 0? This will be said later (I do not know now).
    • Return value: The wrong time to return-1, is correct to return to the 0,c language of the habit is correct to return 0, wrong to pass back the wrong code.
  • Line 21st: bzero is to specify the bit space is all clear to 0, this is not ANSI C standard function, ANSI C standard function is memset, but bzero most of the platform also has support, defined in String.h. The two parameters that are included are as follows:
    • First: To clear the address of 0.
    • Second: The length of the address space.
  • Line 22nd to 24th: Set the value of the server address, which is the variable declared on line 15th, struct SOCKADDR_IN This structure is to pass in some values during bind, these three values are as follows:
    • Sin_family: As indicated by the second argument of the socket, this refers to the use of TCP messaging.
    • SIN_ADDR.S_ADDR: This specifies that Inaddr_any is a socket connection that allows any address to be accepted, and that the HTONL function called before the setting is not related to the platform, and that the different OS have some characters that are not necessarily the same in the order of high and low bits. Through this function can eliminate this kind of platform dependency, all turn to the order of the network.
    • Sin_port: Specifies to bind to that port,htons this function and htonl are all used to remove the platform dependencies, and the difference is that the htons is used in the change of bits, and htonl is used in the change of bits.
  • Line 26th: Bind is the function that connects the socket to the SOCKADDR, which means that the socket line created by row 19th will allow any address to be connected, and the port that will listen is 1513.
  • Line 27th: Start listening, the maximum number of connections is the value that Lintenq defines, that is, 1024 lines.
  • Line 29th: Create an endless loop here, so this server will continue to execute until the user presses CTRL-C.
  • Line 30th: The server stops at the accept to wait for the client to connect, the parameters are as follows:
    • First: Through the listenfd of the description, the 26th and 27 lines listen to the relevant numbers.
    • Second to third: Wait until I get the idea. Xd
    • Return value: After the connection is established, the link descriptor (connected descriptor) is returned, and this description is used to connect to the new client line.
  • Line 32nd: To get the current system time, this time function is fixed in the time.h target file.
  • Line 33rd: snprintf function definition in stdio.h, and sprintf the largest difference in the second part of the snprintf, the space size of the first reference is pointed out, which prevents the actual string length from being passed over the space declared by the first.
  • Line 34th: Write the result to the client, where you can see that the first part is the return value of the accept, so you can tell the system to pass the information to the client.
  • Line 36th: Close the socket connection to the client.

1#include <stdio.h>2#include <sys/socket.h>3#include <sys/types.h>4#include <netinet/inch.h>5#include <strings.h>6#include <arpa/inet.h>7 8 Const intMAXLINE = -;9 Ten voidErr_sys (Const Char*x, ...) One { A perror (x); -     //exit (1); - } the  - voidErr_quit (Const Char*x, ...) - { - perror (x); +     //exit (1); - } +  A intMainintargcChar**argv) at { -     intsockfd, N; -     CharRecvline[maxline +1]; -     structsockaddr_in servaddr; -  -     if(ARGC! =2) { inErr_quit ("usage:a.out <IPaddress>"); -         return 1; to     } +  -     if(SOCKFD = socket (af_inet, Sock_stream,0)) <0) { theErr_sys ("Socket Error"); *         return 1; $     }Panax Notoginseng  -Bzero (&AMP;SERVADDR,sizeof(SERVADDR)); theservaddr.sin_family =af_inet; +Servaddr.sin_port = htons (1513); A     if(Inet_pton (Af_inet, argv[1], &servaddr.sin_addr) <=0) theErr_quit ("Inet_pton error for%s", argv[1]); +  -     if(Connect (SOCKFD,structSOCKADDR *) &servaddr,sizeof(SERVADDR)) <0) $Err_sys ("Connect Error"); $  -      while((n = Read (SOCKFD, Recvline, MAXLINE)) >0) { -Recvline[n] =0; the         if(Fputs (recvline, stdout) = =EOF) -Err_sys ("fputs Error");Wuyi     } the  -     if(N <0) { WuErr_sys ("Read Error"); -         return 1; About     } $  -     return 0; -}
    • Line 41st: When the client program is executed, the Ip,inet_pton function to bring in the server is to convert the text format of the IP into the binary format needed to connect to the next call.
    • Line 44th: Call connect to server.
    • Line 47th: Using read to fetch the value of the server return, the three parameters are as follows:
      • First: The socket descriptor, line 33rd establishes the number of times the socket is logged.
      • The second part: the space in which the value to be read is to be placed.
      • The third part: the maximum length value of the space that is placed.
    • Line 49th: Write the results to the standard Caur output device.

When testing, execute the server and then perform the client,client end showing the following results:

Use C to write the socket program under Linux

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.