如何修复C ++中的“对`gethostbyname(char *)'的未定义引用”错误

时间:2019-07-26 12:23:18

标签: c++

我是c ++的新手,并且想使用套接字在主文件中使用包含头类来发送邮件。

这是针对Linux的,过去我尝试并实现了使用套接字发送电子邮件的方式,但不包含任何头文件。但是需要将mailer类添加到主文件中。在头文件和cpp编译期间,我得到了错误“未定义对`gethostbyname(char *)的引用”。 我尝试编译脚本的命令是“ g ++ -Wall Mailer.cpp”

Mailer.h

using namespace std;
#define HELO "HELO 192.168.1.1\r\n"
#define DATA "DATA \r\n"
#define QUIT "QUIT\r\n"

class Mailer {

private:
    int sock;
    struct sockaddr_in server;
    char buf[BUFSIZ + 1];
    int len;
    char* host_id = "mail.test.com";
    char* from_id = "test@test.com";
    char* to_id = "ttttttt@test.com";
    char* sub = "testr\n";
    char wkstr[100] = "hello how r u\r\n";

public:
    Mailer();
    struct hostent *hp, *gethostbyname(char *host_id);
    void send_socket(char* s);
    void read_socket();
};
#endif

Mailer.cpp

#include "Mailer.h"

void Mailer::send_socket(char* s)
{
    write(sock, s, strlen(s));
    write(1, s, strlen(s));
    //printf("Client:%s\n",s);
}

//=====Read a string from the socket=====*/

void Mailer::read_socket()
{
    len = read(sock, buf, BUFSIZ);
    write(1, buf, len);
    //printf("Server:%s\n",buf);
}

Mailer::Mailer()
{

    /*=====Create Socket=====*/
    sock = socket(AF_INET, SOCK_STREAM, 0);
    if (sock == -1) {
        perror("opening stream socket");
        exit(1);
    }
    else
        cout << "socket created\n";

    /*=====Verify host=====*/
    server.sin_family = AF_INET;
    hp = gethostbyname(host_id);
    if (hp == (struct hostent*)0) {
        fprintf(stderr, "%s: unknown host\n", host_id);
        exit(2);
    }

    /*=====Connect to port 25 on remote host=====*/
    memcpy((char*)&server.sin_addr, (char*)hp->h_addr, hp->h_length);
    server.sin_port = htons(25); /* SMTP PORT */
    if (connect(sock, (struct sockaddr*)&server, sizeof server) == -1) {
        perror("connecting stream socket");
        exit(1);
    }
    else
        cout << "Connected\n";
    /*=====Write some data then read some =====*/
    read_socket(); /* SMTP Server logon string */
    send_socket(HELO); /* introduce ourselves */
    read_socket(); /*Read reply */
    send_socket("MAIL FROM: ");
    send_socket(from_id);
    send_socket("\r\n");
    read_socket(); /* Sender OK */
    send_socket("VRFY ");
    send_socket(from_id);
    send_socket("\r\n");
    read_socket(); // Sender OK */
    send_socket("RCPT TO: "); /*Mail to*/
    send_socket(to_id);
    send_socket("\r\n");
    read_socket(); // Recipient OK*/

    send_socket(DATA); // body to follow*/
    send_socket("Subject: ");
    send_socket(sub);
    read_socket(); // Recipient OK*/
    send_socket(wkstr);
    send_socket(".\r\n");
    read_socket();
    send_socket(QUIT); /* quit */
    read_socket(); // log off */

    //=====Close socket and finish=====*/
    close(sock);
    exit(0);
}

0 个答案:

没有答案