UNIX环境高级编程c语言---本地通信

这篇博客探讨了在UNIX环境下进行高级编程时的本地通信,包括基于UDP和TCP协议的方法。介绍了AF_UNIX常用于进程间通信,而AF_INET和AF_INET6则分别对应IPv4和IPv6的网络通信。内容涵盖了服务器和客户端的实现。
摘要由CSDN通过智能技术生成

网络通信

在这里插入图片描述
参数:
AF_UNIX/AF_LOCAL/AF_FILE: 本地通信(进程间通信);
AF_INET: 基于TCP/IPv4(32位IP地址)的网络通信;
AF_INET6: 基于TCP/IPv6(128位IP地址)的网络通信;
AF_PACKET: 基于底层包接口的网络通信。

type - 通信协议,取值:

SOCK_STREAM: 数据流协议,即TCP协议;
SOCK_DGRAM: 数据报协议,即UDP协议。

protocol - 特别通信协议,一般不用,置0即可。

成功返回套接字描述符,失败返回-1。

本地通信

在这里插入图片描述

基于UDP协议的本地通信

服务器

#include <unistd.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/un.h>
#include <stdbool.h>

#define SOCK_FILE "/tmp/socket"

int main(){
   
	printf("1.服务器创建socket文件描述符.\n");
	int sfd = socket(AF_LOCAL,SOCK_DGRAM,0);
	if(sfd == -1){
   
		perror("socket");
		return -1;
	}
	printf("2.准备物理通信地址.\n");
	struct sockaddr_un addr;
	addr.sun_family = AF_LOCAL;//和创建socket时指定的domain取一样的值
	strcpy(addr.sun_path,SOCK_FILE);
	socklen_t len = sizeof(addr);
	printf("3.socket套接字绑定物理地址.\n");
	int ret = bind(sfd,(const struct sockaddr*)&addr,len);
	if(ret == -1){
   
		perror("bind");
		return -1;
	}
	char buf[1024] = {
   };
	while(true){
   
		//1.接收客户端的消息
		
		ret = read(sfd,buf,1024);
		if(ret == -1){
   
			perror("read");
			break;
		}
		printf("recv: %s",buf);
		if(strcmp(buf
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

HOVL_C++

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值