|
楼主 |
发表于 2005-5-24 16:31:38
|
显示全部楼层
我的代码如下,望赐教!
/*fwq.c
*/
#include <stdio.h>
#include <sys/types.h>
#include <sys/fcntl.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <errno.h>
int port=8000;
int main(int argc,char *argv[])
{
char c,buf[20480];
char filename[30];
int fromlen,source;
int n=0;
FILE *target;
char *strs="\n receiving file";
register int s,ns,k;
struct sockaddr_in sin;
s=socket(AF_INET,SOCK_STREAM,0);
if(s<0){
perror("get socket no!!!");
exit(3);
}
bzero(&sin,sizeof(sin));
sin.sin_family=AF_INET;
sin.sin_port=htons(port);
sin.sin_addr.s_addr=INADDR_ANY;
if(bind(s,(struct sockaddr *)&sin,sizeof(sin))<0){
perror("bind socket no!!!");
close(s);
exit(4);
}
if(listen(s,5)<0){
perror("server:listen");
exit(5);
}
printf("%s",strs);
while(1){
if((ns=accept(s,(struct sockaddr *)&sin,&fromlen))<0){
perror("server:accept");
exit(6);
}
/*while((k=read(ns,file,sizeof(file)))>0){
write(1,"filename:",9);
printf("%s",file);
}*/
sprintf(filename,"pic%d.jpg",n++);
while(k=read(ns,buf,sizeof(buf))>0)
if((target=fopen(filename,"wb"))!=NULL){
fwrite(buf,1,sizeof(buf),target);
printf("\n received succeeded");
}
close(ns);
fclose(target);
}
}
/*
khj
*/
#include <stdio.h>
#include <sys/types.h>
#include <sys/fcntl.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <errno.h>
#include <sys/io.h>
#include <string.h>
//char *host_name="127.0.0.1";
int port=8000;
int main(int argc,char *argv[])
{
char buf[20480],*file;
char *host_name;
host_name=argv[1];
file=argv[2];
FILE *source;
register int s;
size_t k;
struct sockaddr_in sin;
struct hostent *hp;
printf("\n");
if((source=fopen(file,"rb"))<0){
perror("file open");
exit(1);
}
printf("\n sending,wait!");
hp=gethostbyname(host_name);
if(hp==NULL){
perror("get address failure!");
exit(1);
}
s=socket(AF_INET,SOCK_STREAM,0);
if(s<0){
perror("get socket no!!!");
exit(2);
}
sin.sin_family=AF_INET;
sin.sin_port=htons(port);
sin.sin_addr.s_addr=htonl(INADDR_ANY);
sin.sin_addr.s_addr=((struct in_addr *)(hp->h_addr))->s_addr;
//bcopy(hp->h_addr,&sin.sin_addr,hp->h_length);
printf("\n connecting with server!");
if(connect(s,(void *)&sin,sizeof(sin))<0){
perror("connect!!");
exit(3);
}
lseek(source,0L,0);
//write(s,file,strlen(file));
while((k=fread(buf,1,sizeof(buf),source))>0){
write(s,buf,k);
printf("\n send success!\n");
}
printf("\n send %d\n",strlen(buf));
close(s);
close(source);
return 0;
}
真的很感谢楼上的这位朋友,希望你能不厌其烦,给我指点!
再次谢谢啊 |
|