如何确定接口名称 [英] how to determine interface name

查看:488
本文介绍了如何确定接口名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些代码用SOCK_RAW套接字发送tcp包.我的程序只有一个参数:主机名

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);

在评论中,我解释了这个问题,请澄清:我如何确定我的源IP地址,这将取决于我发送软件包的位置.我不想放置设备的程序名称,它可能是tun0和wlan0以及My_Custom_Net_Interface_0012.是否有一种简单的机制来仅知道目的地才可以找到src地址?

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.

我找到了答案:

    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

推荐答案

我找到了答案:

    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)

– Ivan Ivanovich

这篇关于如何确定接口名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆