当前位置: 代码迷 >> 综合 >> 网络通信—本地通信
  详细解决方案

网络通信—本地通信

热度:10   发布时间:2023-11-24 09:40:47.0

O(∩_∩)O 冲冲冲 =====( ̄▽ ̄*)


1.创建套接字

	int socket(int domain,int type,int protocol);domain值:1.AF_UNIX ,AF_LOCAL  本地通信2.AF_INET 为IPv43.AF_INET6为IPv6type值:SOCK_STREAM	数据流SOCK_DGRAM	数据报protocol:特别通信协议 ,一般不用,置0即可

2.准备通信地址

 基本地址类型struct	sockaddr{as_family_t sa_family;		//地址族char sa_data[14];			//地址值};本地地址类型struct sockaddr_un {sa_family_t sun_family;	//地址族char sun_path[];				//套接字文件路径};

3.将套接字和通信地址绑定在一起

int bind(int socked,const struct sockaddr*,socklen_t addrlen);

4.建立连接

int connect(int sockfd,const struct sockaddr*,socklen_t addrlen);

5.用读写文件的方式通信: read/write
6.close

服务器:

#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/un.h>#define SOCK_FILE "/tmp/sock"int main(){
    int sockfd = socket(AF_LOCAL,SOCK_DGRAM,0);if(sockfd == -1){
    perror("sockfd");return -1;}struct sockaddr_un addr;addr.sun_family = AF_LOCAL;strcpy(addr.sun_path,SOCK_FILE);socklen_t len = sizeof(addr);int ret = bind(sockfd,(const struct sockaddr *)&addr,len);if(ret == -1){
    perror("bind");return -1;}while(1){
    char buf[128] = {
    };ret = read(sockfd,buf,sizeof(buf));if(ret == -1){
    perror("read");break;}printf("server:%s\n",buf);if(strcmp(buf,"quit!") == 0){
    printf("退出成功\n");break;}}close(sockfd);unlink(SOCK_FILE);return 0;	
}

客户端:

#include <stdio.h>#include <string.h>#include <sys/socket.h>#include <sys/types.h>#include <unistd.h>#include <sys/un.h>#define SOCK_FILE "/tmp/sock"int main(){
    int sockfd = socket(AF_LOCAL,SOCK_DGRAM,0);if(sockfd == -1){
    perror("sockfd");return -1;}struct sockaddr_un addr;addr.sun_family = AF_LOCAL;strcpy(addr.sun_path,SOCK_FILE);socklen_t len = sizeof(addr);int ret = connect(sockfd,(const struct sockaddr *)&addr,len);if(ret == -1){
    perror("bind");return -1;}while(1){
    char buf[128] = {
    };scanf("%s",buf);ret = write(sockfd,buf,strlen(buf));if(ret == -1){
    perror("write");break;}printf("client:%s\n",buf);/* ret = read(sockfd,buf,sizeof(buf));printf("%d\n",sockfd);printf("ret:%d\n",ret);printf("me:%s\n",buf);*/}close(sockfd);return 0;	}