#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <sys/time.h>
int main(int argc, char * argv [])
{
/* 1. getaddrinfo
2. create a new socket
3. connect to the socket
4. send data */
//Variables Declaration
struct addrinfo hints, * res;
int status; int socket_id;
//clear hints
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = AI_PASSIVE;
char sever_ip_default[100]="127.0.0.1";
char sever_port_default[100]="6666";
char * p_sever_ip = NULL;
char * p_sever_port = NULL;
if(argc>=2)
p_sever_ip = argv[1];
else
p_sever_ip = sever_ip_default;
if(argc>= 3)
p_sever_port = argv[2];
else
p_sever_port = sever_port_default;
printf("Sever ip is %s and port is %s\n",p_sever_ip,p_sever_port);
//status = getaddrinfo("127.0.0.1","6666", &hints, &res);
status = getaddrinfo(p_sever_ip,p_sever_port, &hints, &res);
if(status != 0)
{
fprintf(stderr, "Error getaddrinfo\n");
exit(1);
}
socket_id = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
if(socket_id < 0)
{
fprintf(stderr, "Error socket \n");
exit(2);
}
struct timeval tv_begin, tv_end, tv_value;
gettimeofday(&tv_begin, NULL);
status = connect(socket_id, res->ai_addr, res->ai_addrlen);
gettimeofday(&tv_end, NULL);
tv_value.tv_sec = tv_end.tv_sec - tv_begin.tv_sec;
tv_value.tv_usec = tv_end.tv_usec - tv_begin.tv_usec;
printf("connect time:%lds and %ldus\n",tv_value.tv_sec,tv_value.tv_usec);
if(status < 0)
{
fprintf(stderr, "Error connect \n");
exit(3);
}
int numbytes = 0;
char buf[10];
numbytes = recv(socket_id,buf,10,0);
if(numbytes == -1)
{
fprintf(stderr, "Error receive \n");
exit(4);
}
buf[numbytes] = '\0';
printf("Received %s \n", buf);
freeaddrinfo(res);
close(socket_id);
return 0;
}
参考链接:http://code.runnable.com/VXjZAA1cltc0LP9r/simple-tcp-client-code-for-c%2B%2B-and-socket
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)