static int Tcp1SocketCollectdata(unsigned char * cmd, int cmd_len,
unsigned char * data, int data_len)
{
int sock;
struct sockaddr_in server;
int received = 0;
/* Create the TCP socket */
if((sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)
{
printf("Tcp1SocketCollectdata create socket failed!\n");
return 0;
}
struct timeval tv;
tv.tv_sec = 3; /* 3 Secs Timeout */
tv.tv_usec = 0; // Not init'ing this can cause strange errors
setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, (char *)&tv, sizeof(struct timeval));
/* Construct the server sockaddr_in structure */
memset(&server, 0, sizeof(server)); /* Clear struct */
server.sin_family = AF_INET; /* Internet/IP */
server.sin_addr.s_addr = inet_addr("192.168.0.2"); /* IP address */
server.sin_port = htons(6666); /* server port */
/* Establish connection */
if(connect(sock,
(struct sockaddr *) &server,
sizeof(server)) < 0)
{
printf("Tcp1SocketCollectdata connect socket failed!\n");
close(sock);
return 0;
}
if(send(sock, cmd, cmd_len, 0) != cmd_len) {
printf("Tcp1SocketCollectdata sent cmd failed!\n");
close(sock);
return 0;
}
if((received = recv(sock, data, data_len, 0)) < 1) {
printf("Tcp1SocketCollectdata receive failed!\n"); close(sock);
return 0;
}
// 校验
printf("Tcp1SocketCollectdata received %d bytes\n", received); close(sock);
return 0;
}
|