验证中...
封装函数
Raw Copy
#include"network.h"
#include<stdlib.h>
#include<sys/socket.h>
#include<sys/types.h>
#include<stdio.h>
#include<arpa/inet.h>
#include<unistd.h>
#include<getch.h>
//创建网络连接
Network* open_network(char c_or_s,int type,char* ip,uint16_t port)
{
//在堆上创建Network结构
Network* nw = malloc(sizeof(Network));
if(NULL == nw)
{
perror("network malloc");
return NULL;
}
//创建socket对象
nw->fd = socket(AF_INET,type,0);
if(0 > nw->fd)
{
perror("network socket");
free(nw);
return NULL;
}
//准备通信地址
nw->addr.sin_family = AF_INET;
nw->addr.sin_port = htons(port);
nw->addr.sin_addr.s_addr = inet_addr(ip);
nw->len = sizeof(nw->addr);
nw->type = type;
if('s' == c_or_s)
{
if(bind(nw->fd,(SP)&nw->addr,nw->len))
{
perror("network bind");
free(nw);
return NULL;
}
if(SOCK_STREAM == type&listen(nw->fd,50))
{
perror("network listen");
free(nw);
return NULL;
}
}
else if(SOCK_STREAM == type)
{
if(connect(nw->fd,(SP)&nw->addr,nw->len))
{
perror("network listen");
free(nw);
return NULL;
}
}
return nw;
}
//TCP 的server专用
Network* accept_network(Network* nw)
{
if(SOCK_STREAM != nw->type)
{
printf("network accept socket type error!\n");
return NULL;
}
Network* clinw = malloc(sizeof(Network));
if(NULL == clinw)
{
perror("network accept malloc");
return NULL;
}
clinw->type = nw->type;;
clinw->len = sizeof(clinw->addr);
clinw->fd = accept(nw->fd,(SP)&clinw->addr,&clinw->len);
if(0 > clinw->fd)
{
perror("network accept");
free(clinw);
return NULL;
}
return clinw;
}
//发送数据
int nsend(Network* nw,void* buf,uint32_t len)
{
if(SOCK_STREAM == nw->type)
{
return send(nw->fd,buf,len,0);
}
else if(SOCK_DGRAM == nw->type)
{
return sendto(nw->fd,buf,len,0,(SP)&nw->addr,nw->len);
}
return -1;
}
//接收数据
int nrecv(Network* nw,void* buf,uint32_t len)
{
if(SOCK_STREAM == nw->type)
{
return recv(nw->fd,buf,len,0);
}
else if(SOCK_DGRAM == nw->type)
{
return recvfrom(nw->fd,buf,len,0,(SP)&nw->addr,&nw->len);
}
return -1;
}
//关闭网络连接
int close_network(Network* nw)
{
if(close(nw->fd))
{
perror("network close");
}
free(nw);
}
//输入密码
char* get_passwd(char* passwd,bool is_show,size_t size)
{
int count=0;
do{
if(NULL == passwd)return NULL;
char val = getch();
if(val==127)
{
if(count>0)
{
if(is_show)
{
printf("\b \b");
count--;
}
}continue;
}
else if(val == 10)
{
break;
}
passwd[count++]=val;
if(is_show)printf(" ");
}while(count<size-1);
passwd[count]='\0';
return passwd;
}
void clear_stdin(void)
{
stdin->_IO_read_ptr = stdin->_IO_read_end;
}

Comment list( 0 )

You need to Sign in for post a comment

Help Search