linux 网络编程之最简单的tcp通信客户端

编写一个最为简单的tcp通信客户端。代码如下:

#include 
#include 
using namespace std;

#include 
#include 
#include 
#include 
#include 

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;
}


你可能感兴趣的:(网络通信编程)