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);
}