吾爱破解 - 52pojie.cn

 找回密码
 注册[Register]

QQ登录

只需一步,快速开始

查看: 1716|回复: 1
收起左侧

[C&C++ 原创] 记录用C语言实现socket通信

[复制链接]
wzqfwzy 发表于 2020-12-28 15:20
因近期准备找工作,就翻出笔记看了下,整理出来大家看下指正下(ps:为什么发帖时没有C/C++的选项)
[C] 纯文本查看 复制代码
//服务端代码

#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>		//INADDR_ANY
#include <string.h>

int main(int argc , char *argv[])
{
	if (argc < 2)			//端口参数,发现停止运行后,服务端端口一直没释放,猜测是非正常退出导致没关闭服务
	{
		return -1;
	}
	int ss = socket(AF_INET, SOCK_STREAM, 0);
	struct sockaddr_in server_sockaddr;
	server_sockaddr.sin_family = AF_INET;
	server_sockaddr.sin_port = htons(atoi(argv[1]));
	server_sockaddr.sin_addr.s_addr = htonl(INADDR_ANY);
	
	if (bind(ss, (struct sockaddr *) &server_sockaddr, sizeof(server_sockaddr) ) == -1 )
	{
		printf("bind error\n");
		return -1;
	}
	
	if (listen(ss, 5) == -1)
	{
		printf("listen error\n");
		return -1;
	}
	
	char buff[1024] = {};
	struct sockaddr_in client_addr;
	socklen_t length = sizeof(client_addr);
	
	int sc = accept(ss, (struct sockaddr*)&client_addr, &length);
	if (sc < 0 )
	{
		printf("sc error\n");
		return -1;
	}
	
	while(1)
	{
		memset(buff, 0, sizeof(buff));
		int len = recv(sc, buff, sizeof(buff), 0);
		printf("recv: %s\n",buff );
		send(sc, buff, sizeof(buff), 0);
	}
	close(sc);
	close(ss);
	return 0;
}


[C] 纯文本查看 复制代码
//客户端代码

#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>		//INADDR_ANY
#include <string.h>

int main(int argc, char* argv[])
{
	if (argc < 2)		//端口参数,发现停止运行后,服务端端口一直没释放,猜测是非正常退出导致没关闭服务
	{
		return -1;
	}
	
	int sc = socket(AF_INET, SOCK_STREAM, 0);
	struct sockaddr_in serveraddr;
	memset(&serveraddr, 0, sizeof(serveraddr));
	serveraddr.sin_family = AF_INET;
	serveraddr.sin_port = htons(atoi(argv[1]));				//服务器端口
	serveraddr.sin_addr.s_addr = inet_addr("127.0.0.1");	//服务器ip
	
	if(connect(sc, (struct sockaddr *)&serveraddr , sizeof(serveraddr)) < 0)
	{
		printf("conn error\n");
		return 0;
	}
	
	char sendbuff[1024];
	char recvbuff[1024];
	while(1)
	{
		fgets(sendbuff, sizeof(sendbuff), stdin);
		send(sc, sendbuff, strlen(sendbuff), 0);
		recv(sc, recvbuff, sizeof(recvbuff), 0);
		printf("recv: %s\n", recvbuff);
		memset(recvbuff, 0, sizeof(recvbuff));
		memset(sendbuff, 0 , sizeof(sendbuff));
		
	}
	
	close(sc);
	
	return 0;
}

免费评分

参与人数 2吾爱币 +1 热心值 +2 收起 理由
善止于水 + 1 谢谢@Thanks!
007nbqaq + 1 + 1 我很赞同!

查看全部评分

发帖前要善用论坛搜索功能,那里可能会有你要找的答案或者已经有人发布过相同内容了,请勿重复发帖。

mikey白嫖怪 发表于 2020-12-28 15:38
加油,加油
您需要登录后才可以回帖 登录 | 注册[Register]

本版积分规则

返回列表

RSS订阅|小黑屋|处罚记录|联系我们|吾爱破解 - LCG - LSG ( 京ICP备16042023号 | 京公网安备 11010502030087号 )

GMT+8, 2024-11-25 22:45

Powered by Discuz!

Copyright © 2001-2020, Tencent Cloud.

快速回复 返回顶部 返回列表