Last active
March 18, 2023 16:58
-
-
Save listnukira/4045436 to your computer and use it in GitHub Desktop.
use getsockname to get ip and port
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 <stdlib.h> | |
#include <string.h> | |
#include <unistd.h> | |
#include <sys/socket.h> | |
#include <netinet/in.h> | |
#include <arpa/inet.h> | |
#define SERVER_ADDR "172.217.160.99" | |
#define SERVER_PORT 80 | |
int main() | |
{ | |
char myIP[16]; | |
unsigned int myPort; | |
struct sockaddr_in server_addr, my_addr; | |
int sockfd; | |
// Connect to server | |
if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) { | |
perror("Can't open stream socket."); | |
exit(-1); | |
} | |
// Set server_addr | |
bzero(&server_addr, sizeof(server_addr)); | |
server_addr.sin_family = AF_INET; | |
server_addr.sin_addr.s_addr = inet_addr(SERVER_ADDR); | |
server_addr.sin_port = htons(SERVER_PORT); | |
// Connect to server | |
if (connect(sockfd, (struct sockaddr *) &server_addr, sizeof(server_addr)) < 0) { | |
perror("Connect server error"); | |
close(sockfd); | |
exit(-1); | |
} | |
// Get my ip address and port | |
bzero(&my_addr, sizeof(my_addr)); | |
socklen_t len = sizeof(my_addr); | |
getsockname(sockfd, (struct sockaddr *) &my_addr, &len); | |
inet_ntop(AF_INET, &my_addr.sin_addr, myIP, sizeof(myIP)); | |
myPort = ntohs(my_addr.sin_port); | |
printf("Local ip address: %s\n", myIP); | |
printf("Local port : %u\n", myPort); | |
return 0; | |
} |
in c++, I was getting a conversion error for
int len
, but fixed it bysocklen_t len = sizeof(my_addr);
updated.
I think there's a missing close(sockfd)
at the end of the function.
so for example:
getsockname(sockfd, (struct sockaddr *) &my_addr, &len);
inet_ntop(AF_INET, &my_addr.sin_addr, myIP, sizeof(myIP));
myPort = ntohs(my_addr.sin_port);
close(sockfd);
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
in c++, I was getting a conversion error for
int len
, but fixed it bysocklen_t len = sizeof(my_addr);