Simple example of socket communication under Linux

Source: Internet
Author: User
Tags socket error htons

Simple example of socket communication under Linux

If you spend too much time thinking on a thing, you'll never get it done.

-bruce Lee

Learning Network programming also for some time, just beginning to read "UNIX network Programming" when, think this thick book is very difficult Ah! Seeing later, it was not so difficult to find. If you are a novice, it is recommended that you see the end of the second section and start writing code. It must be impossible not to write code. See 100 times did not knock once again to realize the clear. After the knock, with the problem to read, you will be more targeted. The speed of improvement is fast, and this is the only way to learn any book or language.

I would like to share with you the Learning Network programming encountered difficulties and not smooth, but also hope to discuss with you the problems encountered, grow together, if you are just beginning to learn network programming, then this article will be able to give you some help, my mailbox: [email protected], reproduced please indicate the source.

about how to introduce this simple example :

--1, Code display, function introduction

--2. First, the functions of the function and the prototype of the function are introduced in the client and server.

-3, about the connection three handshake and the TCP connection is closed when the packet exchange

--4, IPV4, IPV6 socket address structure

-5, some good learning website summary

-6, Code download

Client.c

1#include <stdio.h>2#include <sys/socket.h>3#include <sys/types.h>4#include <stdlib.h>5#include <netinet/inch.h>6#include <errno.h>7#include <string.h>8#include <arpa/inet.h>9#include <unistd.h>Ten  #defineMAXLINE 1024 One  intMainintargcChar**argv) A  { -  Char*SERVINETADDR ="127.0.0.1"; -  intsocketfd; the  structsockaddr_in sockaddr; -  CharRecvline[maxline], sendline[maxline]; -  intN; -   +  if(ARGC! =2) -  { +printf"client <ipaddress> \ n"); AExit0); at  } -   -SOCKETFD = socket (Af_inet,sock_stream,0); -memset (&AMP;SOCKADDR,0,sizeof(SOCKADDR)); -sockaddr.sin_family =af_inet; -Sockaddr.sin_port = htons (10004); inInet_pton (AF_INET,SERVINETADDR,&AMP;SOCKADDR.SIN_ADDR)
- if(Connect (SOCKETFD, (structsockaddr*) &sockaddr,sizeof(SOCKADDR))) < 0)
to { toprintf"Connect error%s errno:%d\n", Strerror (errno), errno); +Exit0); - } the *printf"Send message to server\n"); $ Panax NotoginsengFgets (Sendline,1024x768, stdin); - the if(Send (Socketfd,sendline,strlen (sendline),0)) <0) + { Aprintf"send mes Error:%s errno:%d", Strerror (errno), errno); theExit0); + } - $ Close (SOCKETFD); $printf"exit\n"); -Exit0); -}

-Execute: GCC client.c-o client is started./client before you start your program./server-----------------------------------------

Server.c

1#include <stdio.h>2#include <sys/socket.h>3#include <sys/types.h>4#include <string.h>5#include <netinet/inch.h>6#include <stdlib.h>7#include <errno.h>8#include <unistd.h>9#include <arpa/inet.h>Ten   One  #defineMAXLINE 1024 A  intMainintargcChar**argv) -  { -  intLISTENFD,CONNFD; the  structsockaddr_in sockaddr; -  CharBuff[maxline]; -  intN; -   +memset (&AMP;SOCKADDR,0,sizeof(SOCKADDR)); -   +sockaddr.sin_family =af_inet; ASOCKADDR.SIN_ADDR.S_ADDR =htonl (inaddr_any); atSockaddr.sin_port = htons (10004); -   -LISTENFD = socket (Af_inet,sock_stream,0); -   -Bind (LISTENFD, (structSOCKADDR *) &sockaddr,sizeof(SOCKADDR)); -   inListen (LISTENFD,1024x768); -  to   +printf"Please wait for the client information\n"); -   the   for(;;) *  { $  if(CONNFD = Accept (LISTENFD, (structsockaddr*) (null,null)) ==-1)Panax Notoginseng  { -printf"accpet Socket Error:%s errno:%d\n", Strerror (errno), err No); the  Continue; +  } A   then = recv (Connfd,buff,maxline,0); +Buff[n] =' /'; -printf"recv msg from client:%s", buff); $ Close (CONNFD); $  } - Close (LISTENFD); -}

-Execute: After GCC server.c-o server is started./server Service-side program-------------------------------------------------------

> 1, Code Display, function introduction

   Above this simple socket communication code to implement the function : After sending a message from the client, the server receives this message and displays it on the server (recv msg from client:****).

   

> 2, first introduce the functions of the client and server functions and the prototype of the function.  

    1 #include <sys/socket.h>     2int socket (intintint   protocol); Specifies the desired communication protocol type, the returned file descriptor is similar to the socket descriptor, and we become the socket descriptor, referred to as SOCKFD  

Family: Protocol Family

Family Description
Af_inet IPV4 protocol
Af_inet6 IPv6
Af_local UNIX Domain Protocol (Chapter 15)
Af_route Routing Sockets (chapter 18)
Af_key Key Sockets (Chapter 19)

Type: Types of sockets

Type Description
Sock_stream (Common) BYTE stream sockets
Sock_dgram Datagram sockets
Sock_seqpacket Ordered group sockets
Sock_raw Raw sockets

Protocol: A constant of the protocol type or set to 0to select the system default value for the given combination of family and type

Protocol Description
Ipproto_tcp TCP Transport Protocol
Ipproto_udp UDP Transport Protocol
Ipproto_sctp SCTP Transfer Protocol

#include <arpa/inet.h>int inet_pton (int family,constchar *strptr,  void *addrptr); // successful return 1, format not returned 0, error returned-1
Function: P means that the expression n means that the value will be required in all code written later, so this function is important
The string pointed to by char, stored by the addrptr pointer
His inverse function: the inet_ntop () effect is reversed. You can check the function of Baidu. Because we are not involved in the example, it is not introduced. I'll talk about it later.
It is important to note that when the error occurs, the value of errno is set to Eafnosupport about errno value we will introduce later.
int Connect (int sockfd,conststruct sockaddr* servadd,socklen_t addrlen); //Use the Connect function to establish a connection to the TCP server

> 3, on the connection three times handshake and the TCP connection close time Packet Exchange

> 4, IPV4, IPV6 socket address structure

> 5, some good learning website summary

> 6, code download

Simple example of socket communication 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.