Skip to content

Instantly share code, notes, and snippets.

@wuyongzheng
Created August 25, 2011 15:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wuyongzheng/1170922 to your computer and use it in GitHub Desktop.
Save wuyongzheng/1170922 to your computer and use it in GitHub Desktop.
tcpsr: tcp send & receive utility
/* tcpsr: tcp send & receive utility
* 1. connect to server
* 2. send the data which is read from stdin
* 3. receive until close or timeout
*
* return status: (read code)
* public repo: https://gist.github.com/1170922 */
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <assert.h>
#define BUFSIZE 32768
int getaddr (struct sockaddr_in *addr, char *name, char *port)
{
struct addrinfo hints, *result = NULL;
memset(&hints, 0, sizeof(struct addrinfo));
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = AI_PASSIVE;
hints.ai_protocol = 0;
if (getaddrinfo(name, port, &hints, &result) != 0)
return 1;
assert(result->ai_addr != NULL);
assert(result->ai_addrlen == sizeof(struct sockaddr_in));
memcpy(addr, result->ai_addr, sizeof(struct sockaddr_in));
return 0;
}
int main (int argc, char *argv[])
{
int sock;
struct sockaddr_in addr;
struct timeval timeout;
char buffer[BUFSIZE];
int buffer_len;
if (argc != 3) {
printf("Usage: echo $'GET / HTTP/1.0\\r\\n\\r\\n' | %s www.example.com 80\n", argv[0]);
return 5;
}
if (getaddr(&addr, argv[1], argv[2]))
return 4;
sock = socket(PF_INET, SOCK_STREAM, 0);
assert(sock > 0);
timeout.tv_sec = 120; //TODO timeout option
timeout.tv_usec = 0;
setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof(struct timeval));
if (connect(sock, (struct sockaddr *)&addr, sizeof(struct sockaddr_in)))
return 3;
buffer_len = read(0, buffer, BUFSIZE);
assert(buffer_len >= 0);
if (send(sock, buffer, buffer_len, 0) < 0)
return 2;
buffer_len = 0;
while (buffer_len < BUFSIZE) {
int len = recv(sock, buffer + buffer_len, BUFSIZE - buffer_len, 0);
if (len == 0)
break;
if (buffer_len < 0)
return 1;
buffer_len += len;
}
write(1, buffer, buffer_len);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment