50010623 发表于 2015-11-6 10:38:32

linux c socket 模拟登陆FTP

#include <stdio.h>
#include <iostream>
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <unistd.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#define BUF_SIZE 1024
using namespace std;
int send_msg(int sfd, const char*msg)
{
return write(sfd, msg, strlen(msg));
}
int get_msg(int sfd, string**ppstr, bool oneline = false)
{
int len, tmplen, i = 0;
char buf;
while(tmplen = read(sfd, buf, BUF_SIZE))
{
buf = 0;
len += tmplen;
(*ppstr)->append(buf);
if(oneline) break;
}
return len;
}
int main(int argc, char **argv)
{
int sfd, res;
sfd = socket(AF_INET, SOCK_STREAM, 0);
if(-1 == sfd)
{
cout<<&quot;创建socket出错!&quot;<<endl;
exit(1);
}
cout<<&quot;socket创建成功!&quot;<<endl;
struct sockaddr_in sin;
memset(&sin, 0, sizeof(sockaddr_in));
sin.sin_family = AF_INET;
sin.sin_port = htons(21);
sin.sin_addr.s_addr = inet_addr(&quot;61.164.115.208&quot;);
res = connect(sfd, (sockaddr*)&sin, sizeof(sockaddr_in));
if(-1 == res)
{
cout<<&quot;连接服务器出错!&quot;<<endl;
exit(2);
}
cout<<&quot;连接服务器成功!&quot;<<endl;
res = send_msg(sfd, &quot;&quot;);
if(-1 == res)
{
cout<<&quot;发送消息''时发生错误!&quot;<<endl;
exit(3);
}
string *str = new string;
get_msg(sfd, &str, true);
if(&quot;220&quot; != str->substr(0, 3))
{
exit(4);
}
cout<<str->data()<<endl;
res = send_msg(sfd, &quot;USER wed577\r\n&quot;);
if(-1 == res)
{
cout<<&quot;发送消息'USER wed577'时发生错误!\r\n&quot;<<endl;
exit(5);
}
str->resize(0);
get_msg(sfd, &str, true);
if(&quot;331&quot; != str->substr(0, 3))
{
exit(6);
}
cout<<str->data()<<endl;
res = send_msg(sfd, &quot;PASS 703804wed577\r\n&quot;);
if(-1 == res)
{
cout<<&quot;发送消息'PASS 703804wed577\r\n'时发生错误!&quot;<<endl;
exit(7);
}
str->resize(0);
get_msg(sfd, &str, true);
if(&quot;230&quot; != str->substr(0, 3))
{
exit(8);
}
cout<<str->data()<<endl;
res = send_msg(sfd, &quot;QUIT\r\n&quot;);
str->resize(0);
get_msg(sfd, &str, true);
cout<<str->data()<<endl;
return 0;
}
版权声明:本文为博主原创文章,未经博主允许不得转载。
页: [1]
查看完整版本: linux c socket 模拟登陆FTP