Unix域套接字入门

#include <sys/un.h>
#include <sys/socket.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int
main(int argc, char **argv)
{
        int sockfd;
        socklen_t len;  // unistd.h  
        struct sockaddr_un addr1, addr2;

        if (argc != 2){
                printf("usage: unixbind <pathname>\n");
                exit(1);
        }

        if((sockfd = socket(PF_UNIX, SOCK_STREAM, 0))<0){
                printf("socket error!\n");
                exit(1);
        }

        unlink(argv[1]);                //删除防止存在

        bzero(&addr1, sizeof(addr1));
        addr1.sun_family = PF_UNIX;
        strncpy(addr1.sun_path, argv[1], sizeof(addr1.sun_path)-1);
        bind(sockfd, (struct sockaddr *) &addr1, SUN_LEN(&addr1));
         //len =  (sizeof(*(su)) - sizeof((su)->sun_path) + strlen((su)->sun_path))
        
        len = sizeof(addr2);

        getsockname(sockfd, (struct sockaddr *) &addr2, &len);//获得刚绑定的路径名,值-结果参数;

        printf("bound name = %s, returned len = %d\n", addr2.sun_path, len);

        exit(0);
}


通用套接字地址结构 (sys/socket.h):
typedef unsigned short sa_family_t;  //2 B
struct sockaddr {
        sa_family_t     sa_family;    /* address family, AF_xxx       */
        char            sa_data[14];    /* 14 bytes of protocol address */

IPv4 套接字地址结构(netinet/in.h):
/* Structure describing an Internet socket address. */
struct sockaddr_in
{
    __SOCKADDR_COMMON (sin_);
    in_port_t sin_port;                     /* Port number. */
    struct in_addr sin_addr;            /* Internet address. */

    /* Pad to size of `struct sockaddr'. */
    unsigned char sin_zero[sizeof (struct sockaddr) -  __SOCKADDR_COMMON_SIZE - sizeof (in_port_t) - sizeof (struct in_addr)];     //sin_zero[8]
                           /* 字符数组sin_zero[8]的存在是为了保证结构体struct sockaddr_in的大小和结构体struct sockaddr的大小相等 */
};
下面是struct sockaddr_in中用到两个数据类型,具体定义如下:
/* Type to represent a port. */
typedef uint16_t in_port_t;
 

struct in_addr其实就是32位IP地址
struct in_addr {
        unsigned long s_addr;
};

Unix domain socket地址结构:
struct sockaddr_un{
     sa_family_t sun_family;
     char sun_path[104];   //所以需要macro SUN_LEN来得到真正的长度。
};

getsocketname(int sockfd, struct sockaddr *localaddr, socklen_t *addrlen)
获得与某个套接字关联的本地协议地址结构。

你可能感兴趣的:(unix,socket,domain,sockaddr_in,sockaddr_un)