-
-
Save mpontillo/4403760 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 <stdio.h> | |
#include <sys/socket.h> | |
#include <netinet/in.h> | |
#include <arpa/inet.h> | |
#include <unistd.h> | |
int main(int argc, char* argv[]) | |
{ | |
int s; | |
/* struct in_addr addr; */ | |
struct sockaddr_in dest = { 0 }; | |
dest.sin_family = AF_INET; | |
dest.sin_len = sizeof(struct sockaddr_in); | |
dest.sin_port = 80; | |
if(argc < 2) | |
{ | |
fprintf(stderr, "not enough arguments: must supply destination ip address\n"); | |
return 1; | |
} | |
if(0 == inet_aton(argv[1], &dest.sin_addr)) | |
{ | |
fprintf(stderr, "invalid ip address\n"); | |
return 2; | |
} | |
s = socket(AF_INET, SOCK_DGRAM, 0); | |
if(s) | |
{ | |
struct sockaddr_in sin = { 0 }; | |
int result; | |
socklen_t socklen = sizeof(struct sockaddr_in); | |
sin.sin_family = AF_INET; | |
result = bind(s, (struct sockaddr*) &sin, sizeof(struct sockaddr_in)); | |
if(0 != result) | |
{ | |
perror("bind"); | |
goto exit; | |
} | |
result = connect(s, (struct sockaddr*) &dest, sizeof(struct sockaddr_in)); | |
if(0 != result) | |
{ | |
perror("connect"); | |
goto exit; | |
} | |
result = getsockname(s, (struct sockaddr*) &sin, &socklen); | |
if(0 == result) | |
{ | |
// printf("sin_family=%d, sin_addr.s_addr=%08x, sin_port=%d\n", sin.sin_family, sin.sin_addr.s_addr, sin.sin_port); | |
printf("Source address: %s\n", inet_ntoa(sin.sin_addr)); | |
} | |
else | |
{ | |
perror("getsockname"); | |
} | |
exit: | |
close(s); | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment