编写一个最为简单的tcp通信客户端。代码如下:
#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() { /*创建socket*/ int sd = socket(AF_INET, SOCK_STREAM, 0); if (sd == -1) { cout << "socket create error" << endl; cout << errno << ":" << strerror(errno) << endl; exit(-1); } /*定义服务器端地址*/ 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; /*连接服务器*/ 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); } /*通信*/ 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); } /*退出*/ close(sd); return 0; }
时间: 2024-10-14 10:39:26