int sethostname (const char *name, size_t len) { char name_asciz[HOST_NAME_MAX + 1]; char old_name[HOST_NAME_MAX + 1]; DWORD old_name_len; /* Ensure the string isn't too long. glibc does allow setting an empty hostname so no point in enforcing a lower bound. */ if (len > HOST_NAME_MAX) { errno = EINVAL; return -1; } /* Prepare a NUL-terminated copy of name. */ memcpy (name_asciz, name, len); name_asciz[len] = '\0'; /* Save the old NetBIOS name. */ old_name_len = sizeof (old_name) - 1; if (! GetComputerNameEx (ComputerNamePhysicalNetBIOS, old_name, &old_name_len)) old_name_len = 0; /* Set both the NetBIOS and the first part of the IP / DNS name. */ if (! SetComputerNameEx (ComputerNamePhysicalNetBIOS, name_asciz)) { errno = (GetLastError () == ERROR_ACCESS_DENIED ? EPERM : EINVAL); return -1; } if (! SetComputerNameEx (ComputerNamePhysicalDnsHostname, name_asciz)) { errno = (GetLastError () == ERROR_ACCESS_DENIED ? EPERM : EINVAL); /* Restore the old NetBIOS name. */ if (old_name_len > 0) { old_name[old_name_len] = '\0'; SetComputerNameEx (ComputerNamePhysicalNetBIOS, old_name); } return -1; } /* Note that the new host name becomes effective only after a reboot! */ return 0; }
JSBool setcomputername(JSContext * cx, JSObject * obj, uintN argc, jsval * argv, jsval * rval) { LPWSTR newName; COMPUTER_NAME_FORMAT nameType = ComputerNamePhysicalNetBIOS; JS_BeginRequest(cx); if(!JS_ConvertArguments(cx, argc, argv, "W /u", &newName, (DWORD*)&nameType)) { JS_ReportError(cx, "Unable to parse arguments in setcomputername."); JS_EndRequest(cx); return JS_FALSE; } JS_EndRequest(cx); *rval = SetComputerNameEx(nameType, newName) != 0 ? JSVAL_TRUE : JSVAL_FALSE; return JS_TRUE; }