how to determine interface name

无人久伴 提交于 2020-02-06 04:23:19

问题


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


回答1:


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



来源:https://stackoverflow.com/questions/27412201/how-to-determine-interface-name

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!