📜  sockaddr_in c (1)

📅  最后修改于: 2023-12-03 15:20:10.654000             🧑  作者: Mango

sockaddr_in c

Introduction

Sockaddr_in is a structure defined in the C programming language, which is used to store the IP address and port number of the endpoint of a network connection. It is widely used in network programming, especially in TCP/IP based network programming.

Sockaddr_in is part of the socket library, which enables network communication between machines.

Code snippet

Here's an example of how to use sockaddr_in in C:

#include <stdio.h>
#include <sys/socket.h>
#include <netinet/in.h>

int main()
{
    struct sockaddr_in addr;

    addr.sin_family = AF_INET; // IPv4
    addr.sin_port = htons(80); // the port used for HTTP
    addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK); // the loopback address

    printf("IP address: %s\n", inet_ntoa(addr.sin_addr));
    printf("Port number: %d\n", ntohs(addr.sin_port));

    return 0;
}
Explanation

First, we include the required header files that define the socket library and the sockaddr_in structure.

#include <stdio.h>
#include <sys/socket.h>
#include <netinet/in.h>

Next, we create an instance of the sockaddr_in structure and initialize its fields.

struct sockaddr_in addr;

addr.sin_family = AF_INET; // IPv4
addr.sin_port = htons(80); // the port used for HTTP
addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK); // the loopback address

The sin_family field specifies the address family, which in this case is AF_INET for IPv4.

sin_port sets the port number we want to use for communication. In this example, we're using port 80, which is the default port for HTTP.

sin_addr is a union that contains the IP address of the socket. In this example, we're using the loopback address, which is a reserved IP address that refers to the local machine. The inet_addr() function is used to convert a string representation of an IP address to a binary format used by the sin_addr field.

Finally, we print the IP address and port number of the socket using the inet_ntoa() and ntohs() functions, respectively.

Conclusion

In conclusion, sockaddr_in is a crucial structure in network programming that enables the storage of IP addresses and port numbers for use in communication between machines. It is essential to understand how to use it to be able to develop effective network applications in C.