64,651
社区成员
发帖
与我相关
我的任务
分享
#include <sys/socket.h>
#include <netdb.h>
#include <stdio.h>
#include <string.h>
#include <string>
using std::string;
int Connect(const string& host)
{
int sock = 0;
struct hostent * remoteHost;
if ((remoteHost = gethostbyname(host.c_str())) == 0)
{
printf("get host failed:%s\n", host.c_str());
return 0;
}
struct sockaddr_in pin;
memset(&pin, 0, sizeof(pin));
pin.sin_family = AF_INET;
pin.sin_port = htons(25);
pin.sin_addr.s_addr = ((struct in_addr *)(remoteHost->h_addr))->s_addr;
printf("remote host ip:%s, %u\n", remoteHost->h_addr, pin.sin_addr.s_addr);
if((sock = socket(AF_INET, SOCK_STREAM, 0)) == -1)
{
printf("create socket failed\n");
return 0;
}
if (connect(sock, (const sockaddr*)&pin, sizeof(pin)) == -1)
{
printf("connect failed\n"); // 这里提示连接失败!
return 0;
}
return sock;
}
int main(int argc, const char** argv)
{
int sock = Connect("mail.google.com");
if (sock == 0)
{
return 1;
}
printf("Connect succeed:%d\n", sock);
string fromAddr = "xxx@gmail.com";
string msg;
msg = "mail from:<";
msg.append(fromAddr);
msg.append(">\n");
string toAddr = "xxx@gmail.com";
msg.append("rcpt to:<");
msg.append(toAddr);
msg.append(">\n");
string subject = "ttttt";
string content = "aaaaa";
msg.append("data\n");
msg.append("subject:");
msg.append(subject);
msg.append("\n\n");
msg.append(content);
msg.append("\n.\n");
if (send(sock, msg.c_str(), msg.length(), 0) == -1)
{
printf("send fetching request failed\n");
return 1;
}
char recvBuf[1024];
int l = recv(sock, recvBuf, 1023, 0);
printf("recv len:%d\n", l);
printf("%s\n", recvBuf);
return 0;
}