小河学习日记--网络通信发送篇

#include <stdio.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>

int main()
{
printf(“服务器创建socket…\n”);
int sockfd = socket(AF_INET,SOCK_STREAM,0);
/* int socket(int domain , int type , int protocol);
这个函数的功能是:创建socket描述符。socket可以看作文件系统中的文件描述符。
domain:地址类型。分为本地地址,IPv4,IPv6.
type:通信协议。通信协议分为数据流协议(TCP),数据报协议(UDP).
protocol:特殊的通信协议,一般置为0 */
if(0 > sockfd)//由于socket描述符与文件描述符类似,所以都是创建失败返回-1.
{
perror(“socket”);
return -1;
}

printf(“准备地址…\n”);
struct sockaddr_in addr = {};
addr.sin_family = AF_INET;
addr.sin_port = htons(7777);
addr.sin_addr.s_addr = inet_addr(“47.97.229.46”);
socklen_t len = sizeof(addr);
/* struct sockaddr {
sa_family_t sa_family;
char sa_data[14];
}

struct sockaddr_un
{
_SOCKADDR_COMMON (sun); //地址类型 参看domain
char sun_path[108]; // socket文件的路径
};
struct sockaddr_in
{
_SOCKADDR_COMMON (sin);
in_port_t sin_port; // 端口号 大端字节序
struct in_addr sin_addr; // ip地址 大端4字节整数
}
struct in_addr
{
in_addr_t s_addr;
};
注意:函数接口定义的是sockaddr,而实际提供的是sockaddr_un或sockaddr_in /
printf(“绑定连接服务器…\n”);
if(connect(sockfd,(struct sockaddr
)&addr,len))
{
perror(“bind”);
return -1;
}
/* int connect(int sockfd, const struct sockaddr *addr,socklen_t addrlen);
sockfd:socket描述符
addr:通信目标地址
addrlen:通信地址结构体类型的字节数,使用sizeof计算。
返回值:在不同的编程模型下返回值意义不同 /
for( ; ; );
{
char buf[1024] = {};
printf(">");
gets(buf);
write(sockfd,buf,strlen(buf)+1);
/
发送请求和接受请求有两套函数:read/write和recv/send
read/write:是从文件写入/读出的函数,这里将socket描述符当作文件描述符在用。
recv/send:用法和read/send类似。为网络通信专用,函数参数比read/write多一个,多的是对阻塞模式的判断:MSG_WAITALL为阻塞,MSG_DONTWAIT为不阻塞 */
if(0 == strcmp(“quit”,buf))
{
printf(“通信结束!\n”);
break;
}
printf(“read:”);
read(sockfd,buf,sizeof(buf));
printf("%s\n",buf);
}
close(sockfd);
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值