Created
February 23, 2017 18:51
-
-
Save pi0/d1c00d18eba4d77050a3f2ba4f276176 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <errno.h> | |
#include <sys/types.h> | |
#include <sys/socket.h> | |
#include <netinet/in.h> | |
#include <arpa/inet.h> | |
#include <stdio.h> | |
#include <stdlib.h> | |
#include <string.h> | |
#include <unistd.h> | |
unsigned int get_all_buf(int sock, char* output, unsigned int maxsize) | |
{ | |
char buffer[1024]; | |
int n; | |
unsigned int offset = 0; | |
while((errno = 0, (n = recv(sock, buffer, sizeof(buffer), 0))>0) || | |
errno == EINTR) | |
{ | |
if(n>0) | |
{ | |
if (((unsigned int) n)+offset > maxsize) { fprintf(stderr, "too much data!"); exit(EXIT_FAILURE); } | |
memcpy(output+offset, buffer, n); | |
offset += n; | |
} | |
} | |
if(n < 0) | |
{ | |
fprintf(stderr, "error in get_all_buf!"); | |
exit(EXIT_FAILURE); | |
} | |
return offset; | |
} | |
int main(void) | |
{ | |
struct sockaddr_in stSockAddr; | |
int Res; | |
int SocketFD = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP); | |
if (-1 == SocketFD) | |
{ | |
perror("cannot create socket"); | |
exit(EXIT_FAILURE); | |
} | |
memset(&stSockAddr, 0, sizeof(stSockAddr)); | |
stSockAddr.sin_family = AF_INET; | |
stSockAddr.sin_port = htons(1100); | |
Res = inet_pton(AF_INET, "127.0.0.1", &stSockAddr.sin_addr); | |
if (0 > Res) | |
{ | |
perror("error: first parameter is not a valid address family"); | |
close(SocketFD); | |
exit(EXIT_FAILURE); | |
} | |
else if (0 == Res) | |
{ | |
perror("char string (second parameter does not contain valid ipaddress)"); | |
close(SocketFD); | |
exit(EXIT_FAILURE); | |
} | |
if (-1 == connect(SocketFD, (struct sockaddr *)&stSockAddr, sizeof(stSockAddr))) | |
{ | |
perror("connect failed"); | |
close(SocketFD); | |
exit(EXIT_FAILURE); | |
} | |
/* perform read write operations ... */ | |
char out[1024*1024]; | |
memset(out, 0, sizeof(out)-1); | |
unsigned int len = get_all_buf(SocketFD, out, sizeof(out)-1); | |
printf("%d\n", len); | |
//out[len] = '\0'; | |
//puts(out); | |
int i; | |
for (i=0; i<len; i++) printf("%x\n", out[i]); | |
shutdown(SocketFD, SHUT_RDWR); | |
close(SocketFD); | |
return EXIT_SUCCESS; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment