1

I have some code that sends tcp package with SOCK_RAW socket. My program takes a single parameter: the name of the host

Here is a description of how the program works:

getaddrinfo(argv[1], NULL, hints, &answ) //argv[1] it is host name
....
....
socket(tmp->ai_family, tmp->ai_socktype, tmp->ai_protocol) //tmp = answ->ai_next
....
....
/* filling the tcphdr struct */
send_frame->source = s_port;
send_frame->dest = d_port;
send_frame->seq = seq_num;
send_frame->ack_seq = ack_num;
send_frame->doff = 5;
send_frame->fin = 0;
send_frame->syn = 1;
send_frame->rst = 0;
send_frame->psh = 0;
send_frame->ack = 0;
send_frame->urg = 0;
send_frame->window = 0xffff;
send_frame->check = 0;
/* in this part I form a pseudo tcp header for checksum */
/* but for pseudo header i need a source ip address */
/* but I can not know before, what will be the source address */
/* and I can not form the pseudo header, because I do not know what my source address */
sendto(sock, send_frame, sizeof(struct tcphdr), 0, tmp->ai_addr, tmp->ai_addrlen);

in the comments, I explained the problem, ask for clarity: how i can determine my source ip address, which will depend on where I send package. I do not want to put the program names of my devices, it may be tun0 and wlan0 and My_Custom_Net_Interface_0012. Whether there is a simple mechanism to find the src address, knowing only the destination?

I immediately thought that it is necessary to analyze the routing table, but I need an easier way, if such way are exist.

i found the answer:

    connect(sock, tmp->ai_addr, tmp->ai_addrlen);
    struct sockaddr_in addr;
    socklen_t len = sizeof(struct sockaddr_in);
    getsockname(sock, (struct sockaddr *)&addr, &len);
    printf("%s\n", inet_ntoa(addr.sin_addr));

if the question is of interest, it can let alone, if not, it is possible to remove

Ivan Ivanovich
  • 880
  • 1
  • 6
  • 15
  • Can you be more clear on what you want? In your title, you are asking for interface name. But in the question , you are asking for source IP address. – SSC Dec 11 '14 at 01:26
  • No, I think I need a name to get the address, but I was able to get an address without a name. This can be done by means of functions: connect() getsockname(), Of course this only works after: socket() – Ivan Ivanovich Dec 11 '14 at 06:48
  • If you need to get interface name, you can use [`getifaddrs()`](http://man7.org/linux/man-pages/man3/getifaddrs.3.html). Or you can read [this question](http://stackoverflow.com/q/19227781/1865106), there are several answers. – SSC Dec 11 '14 at 06:53

1 Answers1

0

i found the answer:

    connect(sock, tmp->ai_addr, tmp->ai_addrlen);
    struct sockaddr_in addr;
    socklen_t len = sizeof(struct sockaddr_in);
    getsockname(sock, (struct sockaddr *)&addr, &len);
    printf("%s\n", inet_ntoa(addr.sin_addr));

– Ivan Ivanovich

Armali
  • 18,255
  • 14
  • 57
  • 171