Linux socket basics, linuxsocket
Socket originated from unix, and one of the basic philosophies of unix/linux is "Everything is a file", which can be operated in the "open-> write/read-> close" mode. Socket is an implementation of this mode, and socket is a special file. Some socket functions operate on it (open-> I/O operation-> close ).
An example of a simple client getting the server time:
Server code:
Simple logic for implementing socket on the server
1. Set Basic information of sockaddr_in.
2. Create a socket
3 bind the socket and sockaddr_in information together
4. listen can listen to this socket address at this time (the client sends a connection request to the server through socket connect)
5 The accept TCP server can use this function to receive the request after listening to the request.
</Pre> <pre name = "code" class = "plain"> # include <iostream> # include "unp. h "# include" my_err.h "# define DEFAULT_PORT 8000int main (int argc, const char * argv []) {int listenfd, connfd; struct sockaddr_in servaddr; // server address service address structure necessary information of the storage service char buff [MAXLINE]; // MAXLINE = 4096 time_t ticks; listenfd = Socket (AF_INET, SOCK_STREAM, 0 ); // after creating a socket Socket, the returned id is encapsulated. <0 indicates creation failed. For details, see my_err.h file bzero (& Servaddr, sizeof (servaddr); // clearing this memory is equivalent to initializing servaddr = 0 servaddr. sin_family = AF_INET; // IPV4 protocol servaddr. sin_addr.s_addr = htonl (INADDR_ANY); // automatically obtains the local ip address servaddr. sin_port = htons (DEFAULT_PORT); // port number Bind (listenfd, (SA *) & servaddr, sizeof (servaddr )); // bind a specific address to the socket and bind the configured servaddr server information to the socket Listen (listenfd, LISTENQ ); // listen to the socket 1st parameter socket description. The maximum number of connections that can be queued by the second parameter socket (;;) {Std: cout <"wait connect" <std: endl; connfd = Accept (listenfd, (SA *) NULL, NULL ); // if this function is connected, the request will be accepted. The default value is that the blocking function cannot be obtained. The function will not be executed. The mode is not blocked. // the description of the first parameter socket the description of the second parameter Client servaddr information third parameter the number of bytes occupied by the client servaddr 2 and 3 parameters do not care about can be left blank // return a unique connection id // this way after the connection is established, you can start the network I/O ticks = time (NULL ); snprintf (buff, sizeof (buff), "%. 24s \ r \ n ", ctime (& ticks); Write (connfd, buff, strlen (buff); // Write to this connection using the unique id above The client will receive this write to obtain the data sent by the server for interactive Close (connfd);} std: cout <"Hello, World! \ N "; return 0 ;}
Client code: simple socket logic implemented by the client
1. Set Basic information of sockaddr_in.
2. Create a socket
3 connect to the configured Server
4 if the server has a write, read the information sent by the server through read. The client can also write, and the server can also read
</Pre> <pre name = "code" class = "plain"> # include <iostream> # include "unp. h "# include" my_err.h "int main (int argc, const char * argv []) {int sockfd, n; char recvline [MAXLINE + 1]; struct sockaddr_in servaddr; // if (argc! = 2) // err_quit ("usage:. out <Ipaddress> "); if (sockfd = Socket (AF_INET, SOCK_STREAM, 0) <0) err_sys (" socket error "); // create a socket // The first parameter family specifies the protocol family AF_INET (IPV4) AF_INET6 (IPV6), which is commonly used in the Protocol family) AF_UNIX, etc. // The second parameter type specifies the socket type SOCK_STREAM SOCK_DGRAW SOCK_RAW SOCK_PACKET protocol, etc // The third parameter protocol specifies the protocol IPPROTO_TCP IPPTOTO_UDP IPPROTO_SCTP IPPROTO_TIPC corresponds to tcp udp sctp tipc transmission protocol respectively // note: the above type and protocol cannot be combined at will. For example, SOCK_STREAM and IPPTOTO_UDP cannot be combined. When protocol is 0, select the default Transmission protocol example based on family and type: ANF_INET and SOCK_STREAM select TCP protocol ANF_INET and SOCK_DGRAW select UDP protocol bzero (& servaddr, sizeof (servaddr); servaddr. sin_family = AF_INET; servaddr. sin_port = htons (8000); if (inet_ton (AF_INET, "192.168.1.59", & servaddr. sin_addr) <= 0) // 127.0.0.1 assigns the IP address to the servaddr address after the IP address is converted to err_quit ("inet_pton error for % s", argv [1]); //// inet_ton is the address Conversion Function in linux. It converts the IP address to an if (connect (sockfd, (SA *) & servaddr, sizeof (servaddr )) <0) // connect to the specified server err_sys ("connect error"); while (n = read (sockfd, recvline, MAXLINE)> 0) {// read the information sent from the server> 0 indicates that there is data recvline [n] = 0; if (fputs (recvline, stdout) = EOF) err_sys ("fputs error");} if (n <0) err_sys ("read error"); return 0 ;}
My_err.h File
#ifndef time1_my_err_h#define time1_my_err_h#include <errno.h> /* for definition of errno */#include <stdarg.h> /* ISO C variable aruments */static void err_doit(int, int, const char *, va_list);/* * Nonfatal error related to a system call. * Print a message and return. */voiderr_ret(const char *fmt, ...){ va_list ap; va_start(ap, fmt); err_doit(1, errno, fmt, ap); va_end(ap);}/* * Fatal error related to a system call. * Print a message and terminate. */voiderr_sys(const char *fmt, ...){ va_list ap; va_start(ap, fmt); err_doit(1, errno, fmt, ap); va_end(ap); exit(1);}/* * Fatal error unrelated to a system call. * Error code passed as explict parameter. * Print a message and terminate. */voiderr_exit(int error, const char *fmt, ...){ va_list ap; va_start(ap, fmt); err_doit(1, error, fmt, ap); va_end(ap); exit(1);}/* * Fatal error related to a system call. * Print a message, dump core, and terminate. */voiderr_dump(const char *fmt, ...){ va_list ap; va_start(ap, fmt); err_doit(1, errno, fmt, ap); va_end(ap); abort(); /* dump core and terminate */ exit(1); /* shouldn't get here */}/* * Nonfatal error unrelated to a system call. * Print a message and return. */voiderr_msg(const char *fmt, ...){ va_list ap; va_start(ap, fmt); err_doit(0, 0, fmt, ap); va_end(ap);}/* * Fatal error unrelated to a system call. * Print a message and terminate. */voiderr_quit(const char *fmt, ...){ va_list ap; va_start(ap, fmt); err_doit(0, 0, fmt, ap); va_end(ap); exit(1);}/* * Print a message and return to caller. * Caller specifies "errnoflag". */static voiderr_doit(int errnoflag, int error, const char *fmt, va_list ap){ char buf[MAXLINE]; vsnprintf(buf, MAXLINE, fmt, ap); if (errnoflag) snprintf(buf+strlen(buf), MAXLINE-strlen(buf), ": %s", strerror(error)); strcat(buf, "\n"); fflush(stdout); /* in case stdout and stderr are the same */ fputs(buf, stderr); fflush(NULL); /* flushes all stdio output streams */}intSocket(int family, int type, int protocol){intn; if ( (n = socket(family, type, protocol)) < 0)err_sys("socket error");return(n);}voidBind(int fd, const struct sockaddr *sa, socklen_t salen){if (bind(fd, sa, salen) < 0)err_sys("bind error");}voidClose(int fd){if (close(fd) == -1)err_sys("close error");}voidWrite(int fd, void *ptr, size_t nbytes){if (write(fd, ptr, nbytes) != nbytes)err_sys("write error");}intAccept(int fd, struct sockaddr *sa, socklen_t *salenptr){intn; again:if ( (n = accept(fd, sa, salenptr)) < 0) {#ifdefEPROTOif (errno == EPROTO || errno == ECONNABORTED)#else if (errno == ECONNABORTED)#endif goto again; else err_sys("accept error");}return(n);}voidListen(int fd, int backlog){char*ptr; /*4can override 2nd argument with environment variable */if ( (ptr = getenv("LISTENQ")) != NULL)backlog = atoi(ptr); if (listen(fd, backlog) < 0)err_sys("listen error");}#endif
Comparison of window socket http://blog.csdn.net/tutuboke/article/details/45799667