判断ip是否在线之linux下进程间通信(Unix domain socket)

1、程序实现的功能

(1)、程序pragram_a作为服务器,监听客户端发送过来的ip地址,服务端判断该ip地址是否在线
(2)、程序pragram_b作为客户端,向服务器发送ip地址,发送完后自行退出

2、代码实现

总共三个文件:pragram_a.c、pragram_b.c、makefile

//服务器源码:pragram_a.c
#include <stdio.h>
#include <sys/stat.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <errno.h>
#include <stddef.h>
#include <string.h>
#include<stdlib.h>
#include<unistd.h>

// the max connection number of the server
#define MAX_CONNECTION_NUMBER 100

/* * Create a server endpoint of a connection. * Returns fd if all OK, <0 on error. */
int unix_socket_listen(const char *servername)
{
    int fd;
    struct sockaddr_un un;
    if ((fd = socket(AF_UNIX, SOCK_STREAM, 0)) < 0)
    {
        return(-1);
    }
    int len, rval;
    unlink(servername);               /* in case it already exists */
    memset(&un, 0, sizeof(un));
    un.sun_family = AF_UNIX;
    strcpy(un.sun_path, servername);
    len = offsetof(struct sockaddr_un, sun_path) + strlen(servername);

    /* bind the name to the descriptor */
    if (bind(fd, (struct sockaddr *)&un, len) < 0)
    {
        rval = -2;
    }
    else
    {
        if (listen(fd, MAX_CONNECTION_NUMBER) < 0)
        {
            rval =  -3;
        }
        else
        {
            return fd;
        }
    }

    close(fd);
    return rval;
}

int unix_socket_accept(int listenfd, uid_t *uidptr)
{
    int clifd, len, rval;
    time_t staletime;
    
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值