Write one of the simplest TCP communication clients. The code is as follows:
#include <iostream> #include <cstring>using namespace std; #include <sys/socket.h> #include <sys/ types.h> #include <arpa/inet.h> #include <netinet/in.h> #include <errno.h>int main () {/* Create socket* /int SD = socket (af_inet, sock_stream, 0); if (SD = =-1) {cout << "socket create error" << Endl; cout << errno << ":" << strerror (errno) << Endl; Exit (-1); }/* Define server-side address */struct sockaddr_in ser_addr = {0}; ser_addr.sin_family = af_inet; Ser_addr.sin_port = htons (12222); SER_ADDR.SIN_ADDR.S_ADDR = inet_addr ("192.168.56.11"); int ret = 0;/* Connection Server */ret = connect (SD, (struct sockaddr*) &ser_addr, sizeof (SER_ADDR)); if (ret = =-1) {cout << "Socket connect error" << Endl; cout << errno << ":" << strerror (errno) << Endl; Exit (-1); }/* Communication */ Char buf[100] = "Hello I am a Client"; ret = Send (SD, buf, strlen (buf) +1, 0); if (ret <= 0) {cout << "send Error" << Endl; cout << errno << ":" << strerror (errno) << Endl; Exit (-1); }/* Exit */Close (SD); return 0;}
The simplest TCP communication client for Linux network programming