简体   繁体   English

sockaddr_in 生成的地址是否与 ip 地址不同?

[英]Does sockaddr_in make an address that is differrent than an ip address?

This is what the sockaddr_in struct looks like:这是 sockaddr_in 结构的样子:

struct sockaddr_in
{
    sa_family_t    sin_family; address family
    in_port_t      sin_port;   port in network byte order 
    struct in_addr sin_addr;   internet address 
};


struct in_addr
{
    uint32_t       s_addr;     address in network byte order 
};

From what I understand (and please correct me if I am wrong) the inte.net address (sin_addr.s_addr) is an ip address, but the sockaddr_in structure represents an overall structure for how a socket is set up.根据我的理解(如果我错了请纠正我)inte.net 地址 (sin_addr.s_addr) 是一个 ip 地址,但是 sockaddr_in 结构代表了套接字设置方式的整体结构。

If that is the case, and I wanted to connect to some process running on a server, would I just make a struct sockaddr_in, then change the parameters on it and pass it into a connect() system call, and magically my computer would just know how to connect to that computer?如果是这样的话,我想连接到服务器上运行的某个进程,我会做一个 struct sockaddr_in,然后更改它的参数并将它传递给 connect() 系统调用,神奇的是我的电脑会知道如何连接到那台电脑吗?

Also, is there a system call in C that provides the ip address of the computer its running on?另外,C 中是否有系统调用提供其运行计算机的 ip 地址?

A struct sockaddr_in contains all of the necessary data to connect to an IPv4 endpoint. struct sockaddr_in包含连接到 IPv4 端点的所有必要数据。

The sin_family family member should always be set to AF_.NET . sin_family系列成员应始终设置为AF_.NET Because socket functions expect the address of a struct sockaddr , this tells those functions that the structure it is receiving is actually a struct sockaddr_in .因为套接字函数需要struct sockaddr的地址,这告诉那些函数它正在接收的结构实际上是一个struct sockaddr_in This differentiates it from a struct sockaddr_un which is for Unix domain sockets and a struct sockaddr_in6 which is for IPv6 addresses, among others.这将它与用于 Unix 域 sockets 的struct sockaddr_in6 struct sockaddr_un用于 IPv6 地址的 struct sockaddr_in6 等区分开来。

The sin_port member holds the port number of the remote machine, and the sin_addr member holds the IPv4 address of the remote machine. sin_port成员保存远程机器的端口号, sin_addr成员保存远程机器的 IPv4 地址。

So given those three fields, you have sufficient information to connect to a remote TCP/IP port.所以给定这三个字段,您就有了足够的信息来连接到远程 TCP/IP 端口。

Also, is there a system call in C that provides the ip address of the computer its running on?另外,C 中是否有系统调用提供其运行计算机的 ip 地址?

For a connected socket, you can use getsockname to get the local IP and port of the connected socket.对于已连接的套接字,您可以使用getsockname获取已连接套接字的本地 IP 和端口。 If you want to get all of the address on the local system, use getifaddrs on Linux and BSD.如果您想获取本地系统上的所有地址,请在 Linux 和 BSD 上使用getifaddrs

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM