struct sockaddr_in {
short int sin_family; /* 地址族 */
unsigned short int sin_port; /* 端口号 */
struct in_addr sin_addr; /* IP地址 */
unsigned char sin_zero[8]; /* 填充0 以保持与struct sockaddr同样大小 */
};
这个结构更方便使用。sin_zero用来将sockaddr_in结构填充到与struct sockaddr同样的长度,可以用bzero()或memset()函数将其置为零。指向sockaddr_in 的指针和指向sockaddr的指针可以相互转换,这意味着如果一个函数所需参数类型是sockaddr时,你可以在函数调用的时候将一个指向 sockaddr_in的指针转换为指向sockaddr的指针;或者相反。
很好很强大的linux/unix网络文件传输例子:
最近一直在学习unix网络编程,在最开始传输图片的文件老是会出现多出些字节,后面经过测试和参考网上的文章发现是在处理文件的读和写的最后没有处理好出现了这些问题。现在把程序改进了下,测试了可以传输其它类型的文件。下面一步就是编写视频传输的程序。
//////////////////////// server.c
#include
#include
#include
#include
#include
#include
#define MAXSIZE 100
int main(int argc,char **argv)
{
int server_sockfd,client_sockfd;
int server_len,client_len;
char ch[MAXSIZE];
struct sockaddr_in server_address;
struct sockaddr_in client_address;
if (argc != 2)
{
printf("server:file name/n");
exit(1);
}
server_sockfd = socket(AF_INET,SOCK_STREAM,0);
if(server_sockfd <0)
{
printf("Creating socket error!/n");
exit(1);
}
bzero(&server_address,sizeof(struct sockaddr_in));
server_address.sin_family = AF_INET;
server_address.sin_addr.s_addr = htonl(INADDR_ANY);
server_address.sin_port = htons(5000);
server_len = sizeof(server_address);
int opt = 1;
setsockopt(server_sockfd,SOL_SOCKET,SO_REUSEADDR,&opt,sizeof(opt));
if(bind(server_sockfd,(struct sockaddr *)&server_address,server_len) < 0)
{
perror("Bind error.");
exit(1);
}
if(listen(server_sockfd,5) == -1)
{
printf("listen error!/n");
exit(1);
}
client_len = sizeof(client_address);
client_sockfd = accept(server_sockfd,(struct sockaddr *)&client_address, &client_len);
if(client_sockfd == -1)
{
printf("accept error!/n");
exit(1);
}
FILE *fd = fopen(argv[1],"rb");
if (fd == NULL)
{
printf("file open error!/n");
exit(2);
}
while(!feof(fd))
{
int len = fread(ch,1,MAXSIZE,fd);
write(client_sockfd,ch,len);
}
close(client_sockfd);
fclose(fd);
return 0;
}
////////////////////////////
client.c
#include
#include
#include
#include
#include
#include
#include
#include
#include
#define MAXSIZE 100
int main(int argc,char **argv)
{
int sockfd,len;
int result,count;
char recvs[MAXSIZE];
struct sockaddr_in address;
struct hostent *host;
if (argc != 3)
{
printf("client ip filename/n");
exit(1);
}
host = gethostbyname(argv[1]) ;
if(( sockfd = socket(AF_INET,SOCK_STREAM,0))== -1)
{
printf("socket create error!/n");
exit(1);
}
bzero(&address,sizeof(address));
address.sin_family = AF_INET;
address.sin_addr = *((struct in_addr *)host->h_addr);
address.sin_port = htons(5000);
int opt = 1;
setsockopt(sockfd,SOL_SOCKET,SO_REUSEADDR,&opt,sizeof(opt));
len = sizeof(address);
result = connect(sockfd,(struct sockaddr *)&address,len);
if (result == -1)
{
perror("client");
exit(1);
}
FILE *fd = fopen(argv[2],"wb");
if (fd == NULL)
{
printf("create file error!/n");
exit(1);
}
while(1){
count = read(sockfd,recvs,MAXSIZE);
if (count ==0)
break;
fwrite(recvs,1,count,fd);
}
close(sockfd);
fclose(fd);
return 0;
}