1. 完整代码
#include "cups.h"
#include <errno.h>
#include <iostream>#define HTTP_MAX_URI 1024/** 'validate_name()' - Make sure the printer name only contains valid chars.*/static int /* O - 0 if name is no good, 1 if name is good */
validate_name(const char *name) /* I - Name to check */
{const char *ptr; /* Pointer into name *//** Scan the whole name...*/for (ptr = name; *ptr; ptr++)if (*ptr == '@')break;else if ((*ptr >= 0 && *ptr <= ' ') || *ptr == 127 || *ptr == '/' || *ptr == '\\' || *ptr == '?' || *ptr == '\'' || *ptr == '\"' || *ptr == '#')return (0);/** All the characters are good; validate the length, too...*/return ((ptr - name) < 128);
}/** 'default_printer()' - Set the default printing destination.*/static int /* O - 0 on success, 1 on fail */
default_printer(http_t *http, /* I - Server connection */char *printer) /* I - Printer name */
{ipp_t *request; /* IPP Request */char uri[HTTP_MAX_URI]; /* URI for printer/class *//** Build a CUPS-Set-Default request, which requires the following* attributes:** attributes-charset* attributes-natural-language* printer-uri* requesting-user-name*/httpAssembleURIf(HTTP_URI_CODING_ALL, uri, sizeof(uri), "ipp", NULL,"localhost", 0, "/printers/%s", printer);request = ippNewRequest(IPP_OP_CUPS_SET_DEFAULT);ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_URI,"printer-uri", NULL, uri);ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_NAME, "requesting-user-name",NULL, cupsUser());/** Do the request and get back a response...*/ippDelete(cupsDoRequest(http, request, "/admin/"));if (cupsLastError() > IPP_STATUS_OK_CONFLICTING){std::cout << "[ERROR] occur a error when do cups-request{setDefault}. error is:> " << cupsLastErrorString();return (1);}elsereturn (0);
}int main(int argc, char** argv)
{if(argc < 1) {std::cout << "[ERROR] invalid param."; return 1;}char* printer = argv[1];if (!validate_name(printer)){std::cout << "[ERROR] printer name can only contain printable characters." << std::endl; return (1);}http_t *http = NULL; /* Connection to server */http = httpConnect2(cupsServer(), ippPort(), NULL, AF_UNSPEC, cupsEncryption(), 1, 30000, NULL);if (http == NULL){std::cout << "[ERROR] Unable to connect to server: " << strerror(errno) << std::endl;return (1);}if (default_printer(http, printer))return (1);return 0;
}
2. 调用方式
./app 打印机名字
3. 编译
g++ main.cpp -I./include -L. -lcups -o res
include目录下是编译cups后提供的头文件。
libcups.so也被拷贝到此处。
关于cups的编译,此处不再赘述。。。
4. 效果
root@hg-TR3250:/home/test/add# lpstat -a
Founder-6230CSeries 自从 2023年07月19日 星期三 11时07分06秒 开始接受请求
lanxum-MA9340cdn 自从 2023年07月19日 星期三 11时07分38秒 开始接受请求root@hg-TR3250:/home/test/add#
root@hg-TR3250:/home/test/add#
root@hg-TR3250:/home/test/add# lpstat -d
系统默认目标:Founder-6230CSeriesroot@hg-TR3250:/home/test/add#
root@hg-TR3250:/home/test/add# ./app lanxum-MA9340cdn
root@hg-TR3250:/home/test/add#
root@hg-TR3250:/home/test/add#
root@hg-TR3250:/home/test/add# lpstat -d
系统默认目标:lanxum-MA9340cdn