#include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <signal.h># Include <unistd.h> #include <stdlib.h> #include <assert.h> #include <stdio.h> #include < string.h>static bool stop = false;static void handle_term (int sig)//Kill PID; In another TTY would triggle this signal{stop = true; printf ("Signal SIGTERM catched...\n");} static void Handle_int (int sig)//Ctrl + C; Would triggle this signal{printf ("Signal SIGINT catched...\n"); Stop = true; }//./listen 127.0.0.1 8888 100int Main (int argc, char* argv[]) {signal (SIGTERM, handle_term); Signal (SIGINT, handle_int); if (argc <= 3) {printf ("Usage:%s ip_address port_number backlog\n", basename (Argv[0])); return 1; } const char* IP = argv[1]; int port = atoi (argv[2]); int backlog = Atoi (argv[3]); int sock = socket (pf_inet, sock_stream, 0); ASSERT (sock >= 0); struct sockaddr_in addresS Bzero (&address, sizeof (address)); address.sin_family = af_inet; Inet_pton (Af_inet, IP, &address.sin_addr); Address.sin_port = htons (port); int ret = bind (sock, (struct sockaddr*) &address, sizeof (address)); ASSERT (Ret! =-1); printf ("After bind...\n"); Backlog is the max number of waitting connect in wait queue ret = Listen (sock, backlog); Listen is a none-block function assert (ret! =-1); printf ("After listen...\n"); while (! Stop) {sleep (1); } close (sock); return 0;}
#include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <assert.h># Include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <errno.h> #include < String.h>int Main (int argc, char* argv[]) {if (argc <= 2) {printf ("Usage:%s ip_address Port_numbe r\n ", BaseName (Argv[0])); return 1; } const char* IP = argv[1]; int port = atoi (argv[2]); struct SOCKADDR_IN address; Bzero (&address, sizeof (address)); address.sin_family = af_inet; Inet_pton (Af_inet, IP, &address.sin_addr); Address.sin_port = htons (port); int sock = socket (pf_inet, sock_stream, 0); ASSERT (sock >= 0); int ret = bind (sock, (struct sockaddr*) &address, sizeof (address)); ASSERT (Ret! =-1); printf ("After bind...\n"); RET = Listen (sock, 5); ASSERT (Ret! =-1); printf ("After listen...\n"); The returned client is the client's address sTruct sockaddr_in Client; socklen_t client_addrlength = sizeof (client); int connfd = Accept (sock, (struct sockaddr*) &client, &client_addrlength); Accept is a block function printf ("after accept...\n"); if (CONNFD < 0) {printf ("errno is:%d\n", errno); } else {//#define Inet_addrstrlen, IPV4 address char array length, <netinet/in.h> Char Remo Te[inet_addrstrlen]; printf ("Connected with IP:%s and port:%d\n", Inet_ntop (Af_inet, &client.sin_addr, remote, INET_ADDRSTR LEN), Ntohs (Client.sin_port)); Close (CONNFD); } close (sock); return 0;}
Linux Socket Programming Example