Learning Linux Network Programming (1) __arduino

Source: Internet
Author: User
Tags localhost 8888 socket error htons
One of the main features of the Linux system is that his network is very powerful. With the increasing popularity of the network, web-based applications will be more and more. In this network era, mastered the Linux network programming technology, will everyone in the Invincible, Learning Linux network programming, can let us truly experience the charm of the network. Want to become a real hacker, must master the Network programming technology.
Now there are many books on Linux network programming in the bookstore, the network also has a lot of teaching materials on the network programming, we can go to see. Here I will be with you to understand the secret of Linux network programming, because I learn Linux network programming also began soon, so I said below will certainly have the wrong, but also ask everyone to guide out, here I thank you all.

In this chapter, I will be different from the previous chapters, in front of which I have said briefly, from now on I will be as detailed as possible to explain each function and its usage. Okay, let's take a look at the great glamour of Linux.



1. Linux Network Knowledge Introduction

1.1 Client programs and server-side programs
One of the biggest differences between web programs and ordinary programs is that the Web program is made up of two parts-the client and the server side.

The network program is the first server program to start, waiting for the client's program to run and establish a connection. In general, the service-side program listens on a port until a client's program sends a request.

1.2 Common commands
Because the network program is composed of two parts, so it is troublesome to debug, we need to know some common network commands

Netstat
The command netstat is used to display network information such as network connections, routing tables, and interface statistics. Netstat has many options. The option we often use is-an to display detailed network status. As for the other options, we can get detailed information using the Help manual.

Telnet
Telnet is a program for remote control, but we can use this program to debug our server program. For example, our server program is listening on port 8888, we can use Telnet localhost 8888来 to view the service side condition.

1.3 TCP/UDP Introduction
TCP (Transfer control Protocol) transmission protocol is a connection-oriented protocol, and when our network program uses this protocol, the network ensures that our client and server connections are reliable and secure.

The UDP (user Datagram Protocol) Subscriber Datagram Protocol is not a connection-oriented protocol, which does not guarantee that the connection of our network program is reliable, so the program we are writing now generally uses the TCP protocol.

2. Introduction to Elementary Network functions (TCP)
Linux systems are programmed by providing socket (socket) for network programming. Network program through the socket and several other functions of the call, will return a communication file descriptor, we can take this descriptor as a normal file descriptor to operate, which is the Linux device-Independent Benefits. We can communicate data between networks by reading and writing to descriptors.

2.1 Socket
int socket (int domain, int type,int protocol)

Domain: Describes the host of our network program used by the Communication Association (AF_UNIX and Af_inet, etc.). Af_unix can only be used for single UNIX system interprocess communication, and af_inet is for the internet, allowing communication between remote hosts (when we find that the domain option is pf_* instead of af_* when we man socket, Because GLIBC is a POSIX implementation, it replaces AF with PF, which we can all use.

Type: The communication protocol (Sock_stream,sock_dgram, etc.) we use in our web program Sock_stream indicate that we are using a TCP protocol, which provides sequential, reliable, two-way, and connection-oriented bit streams. Sock_dgram shows that we are using the UDP protocol, which will only provide fixed-length, unreliable, connectionless communications.

Protocol: Because we specified the type, so this place we generally as long as the 0来 instead of the socket for network communication to do basic preparation. Returns a file descriptor on success, returns 1 when it fails, and looks at the details of the error that errno can know.


2.2 Bind
int bind (int sockfd, struct sockaddr *my_addr, int addrlen)

SOCKFD: Is the file descriptor returned by the socket call.

Addrlen: Is the length of the SOCKADDR structure.

MY_ADDR: is a pointer to a sockaddr. There is a definition of sockaddr in the

struct sockaddr{
unisgned short as_family;
Char sa_data[14];
};

However, due to the compatibility of the system, we generally do not use this header file, instead of using another structure (struct sockaddr_in) to replace. There are sockaddr_in definitions in
struct sockaddr_in{
unsigned short sin_family;
unsigned short int sin_port;
struct IN_ADDR sin_addr;
unsigned char sin_zero[8];

We mainly use the Internet, so sin_family is typically set to AF_INET,SIN_ADDR to Inaddr_any to communicate with any host, Sin_port is the port number we want to listen to. Sin_zero[8] is used to populate. Bind binds the local port to the file descriptor returned by the socket. Success is to return 0, the failure is the same as the socket

2.3 Listen
int listen (int sockfd,int backlog)

SOCKFD: Is the file descriptor after bind.

Backlog: Sets the maximum length of the request queue. Use this representation to describe the queue length when there are multiple client programs connected to the server. The Listen function changes the file descriptor for bind to a listening socket. The situation returned is the same as bind.


2.4 Accept
int accept (int sockfd, struct sockaddr *addr,int *addrlen)

SOCKFD: Is the listen file descriptor.

Addr,addrlen is used to fill in the client's program, server-side as long as passing the pointer on it. Bind,listen and accept are server-side functions that, when invoked, can block the server-side program until a client has sent a connection. Accept returns the last server-side file descriptor when successful, at which point the server side can write information to the descriptor. Return at failure-1


2.5 Connect
int connect (int sockfd, struct sockaddr * serv_addr,int addrlen)

Sockfd:socket returns the file descriptor.

SERV_ADDR: Server-side connection information is stored. Where Sin_add is the address of the service side

Length of Addrlen:serv_addr

The Connect function is used by the client to connect to the server end. Return 0,SOCKFD on success returns-1 when the file descriptor that communicates with the server fails.


2.6 Examples

Server-side Programs


/******* Server Program (SERVER.C) ************/
#include
#include
#include
#include
#include
#include
#include
#include

int main (int argc, char *argv[])
{
int sockfd,new_fd;
struct sockaddr_in server_addr;
struct sockaddr_in client_addr;
int sin_size,portnumber;
Char hello[]= "hello! Are you fine?\n ";

if (argc!=2)
{
fprintf (stderr, "usage:%s portnumber\a\n", argv[0]);
Exit (1);
}

if ((Portnumber=atoi (argv[1])) <0)
{
fprintf (stderr, "usage:%s portnumber\a\n", argv[0]);
Exit (1);
}

* Server-side start to create socket descriptor * *
if ((Sockfd=socket (af_inet,sock_stream,0)) ==-1)
{
fprintf (stderr, "Socket error:%s\n\a", Strerror (errno));
Exit (1);
}

/* Server-side FILLED SOCKADDR structure * *
Bzero (&server_addr,sizeof (struct sockaddr_in));
Server_addr.sin_family=af_inet;
Server_addr.sin_addr.s_addr=htonl (Inaddr_any);
Server_addr.sin_port=htons (PortNumber);

/* Bundle SOCKFD Descriptor * *
if (Bind (SOCKFD, (struct sockaddr *) (&AMP;SERVER_ADDR), sizeof (struct sockaddr)) ==-1)
{
fprintf (stderr, "Bind error:%s\n\a", Strerror (errno));
Exit (1);
}

/* Monitor SOCKFD Descriptor * *
if (Listen (sockfd,5) ==-1)
{
fprintf (stderr, "Listen error:%s\n\a", Strerror (errno));
Exit (1);
}

while (1)
{
/* The server is blocked until the client program establishes the connection * *
sin_size=sizeof (struct sockaddr_in);
if ((New_fd=accept (SOCKFD, (struct sockaddr *) (&AMP;CLIENT_ADDR), &sin_size)) ==-1)
{
fprintf (stderr, "Accept error:%s\n\a", Strerror (errno));
Exit (1);
}

fprintf (stderr, "Server get connection from%s\n",
Inet_ntoa (CLIENT_ADDR.SIN_ADDR));
if (Write (New_fd,hello,strlen (hello)) ==-1)
{
fprintf (stderr, "Write error:%s\n", Strerror (errno));
Exit (1);
}
* * This communication is over/
Close (NEW_FD);
/* Loop the next one * *
}
Close (SOCKFD);
Exit (0);
}


Client programs

/******* client program Client.c ************/
#include
#include
#include
#include
#include
#include
#include
#include

int main (int argc, char *argv[])
{
int sockfd;
Char buffer[1024];
struct sockaddr_in server_addr;
struct Hostent *host;
int portnumber,nbytes;

if (argc!=3)
{
fprintf (stderr, "usage:%s hostname portnumber\a\n", argv[0]);
Exit (1);
}

if ((Host=gethostbyname (argv[1])) ==null)
{
fprintf (stderr, "GetHostName error\n");
Exit (1);
}

if ((Portnumber=atoi (argv[2])) <0)
{
fprintf (stderr, "usage:%s hostname portnumber\a\n", argv[0]);
Exit (1);
}

/* Client program started to establish SOCKFD descriptor */
if ((Sockfd=socket (af_inet,sock_stream,0)) ==-1)
{
fprintf (stderr, "Socket error:%s\a\n", Strerror (errno));
Exit (1);
}

/* Customer program to populate the service side of the information * *
Bzero (&server_addr,sizeof (SERVER_ADDR));
Server_addr.sin_family=af_inet;
Server_addr.sin_port=htons (PortNumber);
server_addr.sin_addr=* ((struct in_addr *) host->h_addr);

/* Client initiated connection request/*
If Connect (sockfd, (struct sockaddr *) (&AMP;SERVER_ADDR), sizeof (struct sockaddr)) ==-1)
{
fprintf (stderr, "Connect error:%s\a\n", Strerror (errno));
Exit (1);
}

/* The connection was successful * *
if ((Nbytes=read (sockfd,buffer,1024)) ==-1)
{
fprintf (stderr, "Read error:%s\n", Strerror (errno));
Exit (1);
}
buffer[nbytes]=\;
printf ("I have received:%s\n", buffer);
/* End of Communication *
Close (SOCKFD);
Exit (0);
}


MakeFile
Here we compile using the GNU make utility. For more information on make, see Make use Introduction

######### Makefile ###########
All:server Client
Server:server.c
GCC $^-o $@
Client:client.c
GCC $^-o $@

When you run make, two programs server (server-side) and client (client) run first./server portnumber& (portnumber a number larger than 1204 and not appearing in/etc/services) Just use 8888, then run./client localhost 8888 See what happens. (You can also use Telnet and netstat to try it.) It's one of the simplest web programs, but it's also annoying. There are a number of functions that we haven't explained yet. I will make a detailed explanation in the next chapter.


2.7 Summary
In general, the Web program is made up of two parts-the client and the server side. They are generally established in the following steps:

Server-side
Socket-->bind-->listen-->accept

Client
Socket-->connect

Reproduced from: http://www.linuxeden.com/html/develop/20010111/18727.html

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.