1. 程式人生 > >linux c++ socket入門之tcp client端 .

linux c++ socket入門之tcp client端 .

main.cpp

#include <iostream>
#include <tcp_client.h>

using namespace std;

int main(int argc,char* argv[])
{
        tcp_client tc(argv[1],argv[2]);
        return 0;
}


tcp_client.h

#include <unistd.h>
#include <iostream>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <errno.h>

class tcp_client
{
private:
        int socket_fd;
        char message[4096];
        struct sockaddr_in server_addr;

public:
        tcp_client(char* server_ip,char* server_port);
};


tcp_client.cpp

#include "tcp_client.h"

tcp_client::tcp_client(char* server_ip,char* server_port)
{
       if( (socket_fd = socket(AF_INET,SOCK_STREAM,0)) < 0 ) {
                printf("create socket error: %s(errno:%d)\n)",strerror(errno),errno);
                exit(0);
        }

        memset(&server_addr,0,sizeof(server_addr));
        server_addr.sin_family = AF_INET;
        server_addr.sin_port = htons(atoi(server_port));

        if( inet_pton(AF_INET,server_ip,&server_addr.sin_addr) <=0 ) {
                printf("inet_pton error for %s\n",server_ip);
                exit(0);
        }

        if( connect(socket_fd,(struct sockaddr*)&server_addr,sizeof(server_addr))<0) {
                printf("connect error: %s(errno: %d)\n",strerror(errno),errno);
                exit(0);
        }

        printf("send message to server: \n");
        fgets(message,4096,stdin);

        if( send( socket_fd,message,strlen(message),0 ) < 0 ) {
                printf("send message error\n");
                exit(0);
        }

        close(socket_fd);
        exit(0);

}

執行

./main 192.168.99.131 9527