본문 바로가기

개발 노트/C , C++

[Socket] Get socket information by socket descriptor : getsockname()

반응형

How to get the TCP Client Port number by Socket Descripter?

►  getsockname() function (man_page) return the socket information on second parameter by socket descripter in frisrt parameter

1. Write test.cpp

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <arpa/inet.h>

int main()
{
    char strIP[16] = {0,};
    unsigned short usPort = 0;;
    struct sockaddr_in server_addr, my_addr;
    int sockfd = -1; // default Error

    // Create TCP Client Socket
    if((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
    {
        perror("Can't open stream socket.");
        return -1;
    }

    // Set server_addr
    bzero(&server_addr, sizeof(server_addr));
    server_addr.sin_family = AF_INET;
    server_addr.sin_addr.s_addr = inet_addr("172.16.3.204"); // Server IP
    server_addr.sin_port = htons(80); // Server Port

    // Connect to server
    if (connect(sockfd, (struct sockaddr *) &server_addr, sizeof(server_addr)) < 0)
    {
        perror("Connect server error");
        close(sockfd);
        return -1;
    }

    // Get Client IP and Port
    bzero(&my_addr, sizeof(my_addr));
    socklen_t len = sizeof(my_addr);

    getsockname(sockfd, (struct sockaddr *) &my_addr, &len);

    printf("Local ip address: %s\n", inet_ntoa(my_addr.sin_addr));
    printf("Local port : %u\n", ntohs(my_addr.sin_port)); // Network is Big endian

    return 0;
}

2. Check the result

Compile and execute the program

[root@localhost test]# g++ -o test test.cpp && ./test
Local ip address: 10.211.55.4
Local port : 38804

Check the packet by tcpdump

[root@localhost test]# tcpdump -i eth0 -s 0 -n tcp port 80
tcpdump: verbose output suppressed, use -v or -vv for full protocol decode
19:38:57.622896 IP 10.211.55.4.38804 > 172.16.3.204.http: Flags [S], seq 2413665406, win 14600, options [mss 1460,sackOK,TS val 724875807 ecr 0,nop,wscale 7], length 0
19:38:57.626132 IP 172.16.3.204.http > 10.211.55.4.38804: Flags [S.], seq 3993806964, ack 2413665407, win 32768, options [mss 1460,wscale 1,nop], length 0
19:38:57.626189 IP 10.211.55.4.38804 > 172.16.3.204.http: Flags [.], ack 1, win 115, length 0
19:38:57.626901 IP 10.211.55.4.38804 > 172.16.3.204.http: Flags [F.], seq 1, ack 1, win 115, length 0
19:38:57.627027 IP 172.16.3.204.http > 10.211.55.4.38804: Flags [.], ack 2, win 16384, length 0
19:38:57.633470 IP 172.16.3.204.http > 10.211.55.4.38804: Flags [F.], seq 1, ack 2, win 16384, length 0
19:38:57.633518 IP 10.211.55.4.38804 > 172.16.3.204.http: Flags [.], ack 2, win 115, length 0

참고 : https://gist.github.com/listnukira/4045436

반응형

'개발 노트 > C , C++' 카테고리의 다른 글

[C++ Library] JsonCPP vs Rapid Json  (1) 2018.10.13
MFC와 CppSQLite3U 연동방법  (0) 2018.10.04