Skip to content

Instantly share code, notes, and snippets.

@listnukira
Last active March 18, 2023 16:58
Show Gist options
  • Star 12 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save listnukira/4045436 to your computer and use it in GitHub Desktop.
Save listnukira/4045436 to your computer and use it in GitHub Desktop.
use getsockname to get ip and port
#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;
}
@kunmukh
Copy link

kunmukh commented Apr 3, 2021

in c++, I was getting a conversion error for int len, but fixed it by socklen_t len = sizeof(my_addr);

@listnukira
Copy link
Author

in c++, I was getting a conversion error for int len, but fixed it by socklen_t len = sizeof(my_addr);

updated.

@bucanero
Copy link

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