sockaddr_in 和sockaddr_un的区别

sockaddr_in的结构:

  struct   sockaddr_in   {  
                short   int   sin_family;     
                unsigned   short   int   sin_port;     
                struct   in_addr   sin_addr;     
                unsigned   char   sin_zero[8];     
        };  

sockaddr_un的结构:

#define UNIX_PATH_MAX 108

    struct sockaddr_un {
    sa_family_t     sun_family;     /*PF_UNIX或AF_UNIX */
    char    sun_path[UNIX_PATH_MAX];        /* 路径名 */
    };

sockaddr_in  主要用于不同主机之间的socket编程;

sockaddr_un  主要用于同一个主机中的本地Local socket

例如:

#define UPB_PHP_SOCK_PATH "/var/uc_php_sk"

{

int listenFd;
struct sockaddr_un addr;
socklen_t addrlen;
struct ev_t *ev;


unlink(UPB_PHP_SOCK_PATH);
umask(0);

/* Create UNIX domain socket.  */
listenFd = socket (AF_UNIX, SOCK_STREAM, 0);
    if (listenFd < 0){
SERVER_ERR(" create socket fail \"%s\"!!\n", strerror(errno));
goto error_out;
}

memset (&addr, 0, sizeof (struct sockaddr_un));
addr.sun_family = AF_UNIX;
strcpy (addr.sun_path, UPB_PHP_SOCK_PATH);
addrlen = sizeof (addr.sun_family) + strlen(addr.sun_path);


if(bind(listenFd, (struct sockaddr *) &addr, addrlen) < 0){
SERVER_ERR("unable to bind fd=%d\n", listenFd);
goto closefd_out;
}

if (listen(listenFd, UPB_MAX_LISTEN_NUM>128 ? 128: UPB_MAX_LISTEN_NUM)) {
SERVER_ERR("listen fail fd=%d\n", listenFd);
goto closefd_out;
}
set_nonblock_fd(listenFd);

.................

..............

...............

}


sockaddr_in:


{

int db_fd ;
struct sockaddr_in db_addr;
struct event_t * event = NULL;
struct ev_t *ev = NULL;
char *pl_server;
struct hostent *host;


struct upbt_conf_t *upbt_conf;

upbt_conf = get_upbt_conf();

do {
pl_server = upb_getDbServer(upbt_conf->pl_index);
if (!pl_server) {
return -1;
}
host=gethostbyname(pl_server);
if (!host || host->h_addrtype != AF_INET) {
SERVER_DBG(" parse %s fail \"%s\"!!\n",pl_server , strerror(errno));
goto another_db;
}
memcpy(&db_addr.sin_addr.s_addr,host->h_addr,sizeof(db_addr.sin_addr.s_addr));
SERVER_DBG("USE Datebase Server %s[%s] host = 0x%p\n",pl_server,inet_ntoa(db_addr.sin_addr),host);
db_addr.sin_family = AF_INET;
db_addr.sin_port = htons(UC_PB_PORT);

db_fd = socket(AF_INET, SOCK_STREAM, 0);
if (db_fd < 0){
SERVER_DBG("create socket fail \"%s\"!!\n", strerror(errno));
goto another_db;
}



   if (connect(db_fd, (struct sockaddr *) &db_addr,sizeof(db_addr)) < 0) {
SERVER_DBG("connect to %s fail: %s\n",pl_server ,strerror(errno));
close(db_fd);
goto another_db;
   }

set_nonblock_fd(db_fd);

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值