如何在C中为客户指定IP地址 [英] How to give to a client specific ip address in C

查看:86
本文介绍了如何在C中为客户指定IP地址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试用C实现一个简单的客户端和服务器,但我找不到在线示例,该示例如何为客户端设置特定的IP地址。这就是我到目前为止所得到的:

I am trying to implement a simple client and server in C and I can't find online an example how to set a specific IP address to the client. This is what I got so far:

sockfd = socket(PF_INET, SOCK_STREAM, 0);
if (sockfd == -1)
{
    <some code to handle error>
}
address.sin_family = AF_INET;
address.sin_addr.s_addr = inet_addr(<addressOfTheServer>);
address.sin_port = htons(<portToConnectToServer>);
len = sizeof(address);

int result = connect(sockfd, (struct sockaddr *)&address, len);

在服务器端,我检查客户端IP地址,我总是得到127.0.0.1

On the server side I check for the client IP Address and I always get 127.0.0.1

我想将其更改为其他内容。

I want to change it something different.

推荐答案

如果您想要客户要使用特定的网络接口(例如,因为您有多个网卡)进行连接,则首先需要调用连接之前,对该接口的IP地址> bind(2) 。例如,如果您有两个IP地址分别为192.168.1.100和10.101.151.100的网络接口,则可以使用192.168.1.100地址进行连接:

If you want your client to connect using a specific network interface (say, because you have multiple network cards), then you first need to call bind(2) on that interface's IP address before connecting. For example, if you have two network interfaces with IP addresses 192.168.1.100 and 10.101.151.100, then to connect using the 192.168.1.100 address you could do this:

// Error checking omitted for expository purposes
int sockfd = socket(AF_INET, SOCK_STREAM, 0);

// Bind to a specific network interface (and optionally a specific local port)
struct sockaddr_in localaddr;
localaddr.sin_family = AF_INET;
localaddr.sin_addr.s_addr = inet_addr("192.168.1.100");
localaddr.sin_port = 0;  // Any local port will do
bind(sockfd, (struct sockaddr *)&localaddr, sizeof(localaddr));

// Connect to the remote server
struct sockaddr_in remoteaddr;
remoteaddr.sin_family = AF_INET;
remoteaddr.sin_addr.s_addr = inet_addr(server_ip);
remoteaddr.sin_port = htons(server_port);
connect(sockfd, (struct sockaddr *)&remoteaddr, sizeof(remoteaddr));

这篇关于如何在C中为客户指定IP地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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