socket通信socketpair

这篇文章主要介绍的是socketpair()函数,至于函数的详细介绍,大家可以参看:man socketpair 介绍的还是可以的。下面是中文简介:
函数原型
#include <sys/types.h> 
#include <sys/socket.h> 
int socketpair(int d, int type, int protocol, int sv[2]); 
参数介绍:
socketpair()函数建立一对匿名的已经连接的套接字,其特性由协议族d、类型type、协议protocol决定,建立的两个套接字描述符会放在sv[0]和sv[1]中。
socketpair()函数的原型如下,第1个参数d,表示协议族,只能为AF_LOCAL或者AF_UNIX;
第2个参数type,表示类型,只能为0。
第3个参数protocol,表示协议,可以是SOCK_STREAM或者SOCK_DGRAM。用SOCK_STREAM建立的套接字对是管道流,与一般的管道相区别的是,套接字对建立的通道是双向的,即每一端都可以进行读写。参数sv,用于保存建立的套接字对。

下面是代码:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
int main(int argc,char **argv)
{
        int z;        /* Status return code */
        int s[2];    /* Pair of sockets */
        char *cp;    /* A work pointer */
        char buf[80];    /* work buffer */
        z = socketpair(AF_LOCAL,SOCK_STREAM,0,s);
        if(z == -1)
        {
                printf("creat spcketpair error\n");
                return 1;    /* Failed */
        }
        z = write(s[1],"Hello?",6);
        if(z<0)
        {
                printf("write error\n");
                return 2;    /* Failed */
        }
        printf("write hello? to s[1]\n");
        z = read(s[0],buf,sizeof buf);
        if(z < 0)
        {
                printf("read error\n");
                return 3;    /* Failed */
        }
        printf("Recevie message '%s' from socket s[0]\n",buf);
        z = write(s[0],cp="Go away!",8);
        if(z < 0)
        {
                printf("write error");
                return 4;    /* Failed */
        }
        printf("write Go away! to s[1]\n");
        z = read(s[1],buf,sizeof buf);
        if(z < 0)
        {
                printf("read error\n");
                return 3;    /* Failed */
        }
        buf[z] = 0;    /*NUL terminate */
        printf("Received message '%s' from socket s[1]\n",buf);
        close(s[0]);
        close(s[1]);
        return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值